1. 程式人生 > >【LeetCode】91. Decode Ways(C++)

【LeetCode】91. Decode Ways(C++)

地址:https://leetcode.com/problems/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 a non-empty string containing only digits, determine the total number of ways to decode it.

Example 1:

Input: “12”
Output: 2
Explanation: It could be decoded as “AB” (1 2) or “L” (12).

Example 2:

Input: “226”
Output: 3
Explanation: It could be decoded as “BZ” (2 > 26), “VF” (22 6), or “BBF” (2 2 6).

理解:

需要按位判斷,如果這一位有效的話,可能數和從下一位開始判斷是相同的。如果這兩位有效的話,可能數還要加上從下下一位判斷。
注意這個問題裡,既可以從前向後判斷,又可以從後向前判斷,是一樣的。

實現:

自己實現了一種遞迴的方式,如果本位有效,就判斷後面的,如果本位無效,就返回0。
感覺這種思路其實有些混亂。

class Solution {
public:
	int numDecodings(string s) {
		return ways(s, 0);
	}
private:
	int ways(const string& str, int begin) {
		if (begin >= str.length()) return 1;
		if (str[begin] >= '3')
			return ways(str, begin + 1);
		else
if (str[begin] == '2') { if (begin == str.length() - 1) return ways(str, begin + 1); else { if (str[begin + 1] >= '7') return ways(str, begin + 1); else return ways(str, begin + 1) + ways(str, begin + 2); } } else if (str[begin] == '1') { if (begin == str.length() - 1) return ways(str, begin + 1); else return ways(str, begin + 1) + ways(str, begin + 2); } else return 0; } };

實現2:

這種實現使用了dp,dp就是迭代版的化簡。
從頭開始判斷,dp的第i位存的是s的子串s[0...i-1]的可能解碼方式總數。

class Solution {
public:
	int numDecodings(string s) {
		if (s[0] == '0') return 0;
		else if (s.size() == 1) return 1;

		vector<int> dp(s.size() + 1, 0);
		dp[0] = dp[1] = 1;
		for (int i = 2; i < dp.size(); ++i) {
			if (s[i - 1] > '0') dp[i] = dp[i - 1];
			if (s[i - 2] == '1' || (s[i - 2] == '2'&&s[i - 1] <= '6')) dp[i] += dp[i - 2];
		}
		return dp.back();
	}
};