码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Decode Ways

时间:2015-03-19 07:45:43      阅读:148      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!