[Leetcode] Decode Ways

A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1

'B' -> 2

...

'Z' -> 26

Given an encoded message containing digits, determine the total number of ways to decode it.

For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding "12" is 2.

动态规划,想法跟Climbing Stairs想法一样,形式相同,但是加了一些限制,不是所有情况下都能后传递,所以要写两个判断函数。

 1 class Solution {

 2 public:

 3     bool isLegal(char digit) {

 4         return digit != '0';

 5     }

 6     

 7     bool isLegal(char digit1, char digit2) {

 8         return digit1 == '1' || (digit1 == '2' && digit2 < '7');

 9     }

10     

11     int numDecodings(string s) {

12         if (s.length() == 0) return 0;

13         if (s.length() == 1) return isLegal(s[0]) ? 1 : 0;

14         vector<int> dp(s.length(), 0);

15         if (isLegal(s[0]))  dp[0] = 1;

16         if (isLegal(s[0]) && isLegal(s[1]))  dp[1] = 1;

17         if (isLegal(s[0], s[1])) dp[1] += dp[0];

18         for (int i = 2; i < s.length(); ++i) {

19             if (isLegal(s[i])) dp[i] += dp[i-1];

20             if (isLegal(s[i-1], s[i])) dp[i] += dp[i-2];

21         }

22         return dp[s.length() - 1];

23     }

24 };

最开始想到是的深搜,超时了。看来以后在考虑问题时要把动规的优先级调到深搜广搜的前面。

 1 class Solution {

 2 public:

 3     void getDecode(string &s, int idx, int &res) {

 4         if (idx == s.length()) {

 5             ++res;

 6             return;

 7         }

 8         int val = s[idx] - '0';

 9         getDecode(s, idx + 1, res);

10         if (idx + 1 < s.length()) {

11             val *= 10;

12             val += s[idx+1] - '0';

13             if (val < 27) {

14                 getDecode(s, idx + 2, res);

15             }

16         }

17     }

18     

19     int numDecodings(string s) {

20         int res = 0;

21         getDecode(s, 0, res);

22         return res;

23     }

24 };

 

你可能感兴趣的:(LeetCode)