lintcode 解碼方法
阿新 • • 發佈:2017-08-16
color nco public col 規劃 nbsp memset eof integer
簡單的動態規劃
1 class Solution { 2 public: 3 4 /* 5 * @param s: a string, encoded message 6 * @return: an integer, the number of ways decoding 7 */ 8 int numDecodings(string s) { 9 // write your code here 10 if(s == "" || s[0] == ‘0‘) return 0; 11int dp[110]; 12 13 memset(dp, 0, sizeof(dp)); 14 dp[0] = 1; 15 for(int i = 1; i < s.length(); ++i){ 16 if(s[i] == ‘0‘){ 17 if(s[i - 1] != ‘1‘ && s[i -1] != ‘2‘) return 0; 18 else { 19 dp[i] = dp[i] + (i - 2>= 0 ? dp[i-2] : 1); 20 } 21 } else { 22 if(s[i - 1] == ‘1‘){ 23 dp[i] = dp[i] + (i - 2 >= 0 ? dp[i-2] : 1); 24 dp[i] = dp[i] + dp[i - 1]; 25 } else if(s[i - 1] == ‘2‘){ 26 if(s[i] <= ‘6‘) 27 dp[i] = dp[i] + (i - 2 >= 0 ? dp[i-2] : 1); 28 dp[i] = dp[i] + dp[i - 1]; 29 } else { 30 dp[i] = dp[i] + dp[i - 1]; 31 } 32 } 33 } 34 35 return dp[s.length() - 1]; 36 } 37 };
lintcode 解碼方法