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

13459 ワード

アドレス: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).
理解:
ビットで判断する必要がありますが、このビットが有効であれば、可能数は次のビットから判断するのと同じです.この2人が有効であれば、次の判断を加えなければならないかもしれません.注意この問題では、前から後ろへ判断してもいいし、後から前へ判断してもいいので、同じです.
実装:
自分で再帰的な方法を実現し、本位が有効であれば後のものを判断し、本位が無効であれば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();
	}
};