动态规划。要注意way+=dp[i-1]或dp[i-2]以及way+=1的条件。我看有的人把数组命名为count的。
public class Solution { public int numDecodings(String s) { // Start typing your Java solution below // DO NOT write main() function int len = s.length(); if (len == 0) return 0; int[] dp = new int[len]; for (int i = 0; i < len; i++) { int way = 0; if (s.charAt(i) != '0') { if (i-1 >= 0) { way += dp[i-1]; } else { way += 1; } } if (i-1 >= 0 && (s.charAt(i-1) == '1' || (s.charAt(i-1) == '2' && s.charAt(i) <= '6'))) { if (i-2 >= 0) { way += dp[i-2]; } else { way+= 1; } } dp[i] = way; } return dp[len-1]; } }
第二刷,做繁琐了
class Solution { public: vector<int> ways; int numDecodings(string s) { if (s.size() == 0) return 0; ways.clear(); ways.resize(s.size() + 1); for (int i = 0; i < ways.size(); i++) { ways[i] = -1; } return numDecodingsRe(s, 0); } int numDecodingsRe(const string &s, int start) { if (ways[start] != -1) { return ways[start]; } if (start == s.size()) { ways[start] = 1; return 1; } if (s[start] < '1' || s[start] > '9') { ways[start] = 0; return 0; } if (start == s.size() - 1) { ways[start] = 1; return 1; } if (s[start] == '1') { ways[start] = numDecodingsRe(s, start + 1) + numDecodingsRe(s, start + 2); return ways[start]; } if (s[start] == '2' && s[start + 1] <= '6') { ways[start] = numDecodingsRe(s, start + 1) + numDecodingsRe(s, start + 2); return ways[start]; } ways[start] = numDecodingsRe(s, start + 1); return ways[start]; } };
python3, dp, 注意单个的'0'没有对应编码
class Solution: def numDecodings(self, s: str) -> int: memo = {} # decode ways for s[ : i] for i in range(len(s) + 1): # i, length of sub str if i == 0: memo[i] = 1 elif i == 1: if s[i - 1] == '0': memo[i] = 0 else: memo[i] = 1 else: # i >= 2 nums = 0 if int(s[i - 2:i]) <= 26 and int(s[i - 2:i]) >= 10: nums += memo[i - 2] if s[i - 1] != '0': nums += memo[i - 1] memo[i] = nums return memo[len(s)]