首页 > 其他 > 详细

LeetCode – Refresh – Decode Ways

时间:2015-03-19 07:43:31      阅读:274      评论:0      收藏:0      [点我收藏+]

Simple DP.

Scanning from the end. If current is 0, then no ways as "0", but it can be treated as "10", "20". So do another check whether it can has other combinations from i+2.

But if the last one is "0", there is no way to decode it except len-2 is "1" or "2". So assign one more space to dp hold 1 way for special case.

 1 class Solution {
 2 public:
 3     int numDecodings(string s) {
 4         int len = s.size();
 5         if (len == 0) return 0;
 6         vector<int> dp(len+1, 1);
 7         for (int i = len-1; i >= 0; i--) {
 8             if (s[i] == 0) dp[i] = 0;
 9             else dp[i] = dp[i+1];
10             
11             if (i < len-1 && (s[i] == 1 || (s[i] == 2 && s[i+1] <= 6))) dp[i] += dp[i+2];
12         }
13         return dp[0];
14     }
15 };

 

LeetCode – Refresh – Decode Ways

原文:http://www.cnblogs.com/shuashuashua/p/4349365.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!