Advertisement
jinhuang1102

91. Decode Ways

Jan 19th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. """91. Decode Ways, backtrack递归方法想了很久没想明白。看了discuss知道用dp,创建memo的list,每个index表示在当前所拥有的decode的方式。memo[0] = 1 一个empty string就只有一种decode的方法.memo[1],表示当string的size为一时有多少种decode的方法。从index = 2 开始遍历,每次回溯1 or 2 个 substring 如果符合要求就累加到当前位。最后返回memo第n位
  2. """
  3. class Solution(object):
  4.     def numDecodings(self, s):
  5.         """
  6.        :type s: str
  7.        :rtype: int
  8.        """
  9.         if not s:
  10.             return 0
  11.        
  12.         n = len(s)
  13.         memo = [0] * (n+1)
  14.         memo[0] = 1
  15.         memo[1] = 1 if s[0] != '0' else 0
  16.        
  17.         for i in range(2, n+1):
  18.             first = int(s[i-1:i])
  19.             second = int(s[i-2:i])
  20.            
  21.             if first >= 1 and first <= 9:
  22.                 memo[i] += memo[i-1]
  23.                
  24.             if second >= 10 and second <= 26:
  25.                 memo[i] += memo[i-2]
  26.                
  27.         return memo[n]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement