代码之家  ›  专栏  ›  技术社区  ›  Dawn17

解码方式问题递归解的直觉

  •  0
  • Dawn17  · 技术社区  · 7 年前

    https://www.geeksforgeeks.org/count-possible-decodings-given-digit-sequence/

    在上面的这个问题中,它要求我计算给定数字序列可能的编码数目。

    这个问题可以递归地解决,我们可以对两个子问题进行递归。

    1) If the last digit is non-zero, recur for remaining (n-1) digits and add the result to total count.
    
    2) If the last two digits form a valid character (or smaller than 27), recur for remaining (n-2) digits and add the result to total count.
    

    我确实明白,但我不完全明白为什么会这样解决。

    我基于上述解决方案编写的代码给出了正确的答案。

    def numDecode(s):
        if len(s) == 0 or len(s) == 1: return 1
        count = 0
        if s[n - 1] > '0':
            count = numDecode(s[:n-1])
        if s[n - 2] == '1' or (s[n - 2] == '2' and s[n - 1] < '7'):
            count += rec(s[:n-2])
        return count
    

    然而,我仍然没有抓住这个解决方案背后的直觉。为什么我们要从后面开始?为什么我们要把它分解成两个子问题,取最后一个一位数和两位数?

    谢谢!

    0 回复  |  直到 7 年前