LeetCode91 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).

题源:here;完整实现:here

思路:

动态规划:

dp[i] = dp[i-1]+dp[i-1] if s[i-1], s[i-2] are valid

dp[i] = dp[i-1] if only dp[i-1] valid

代码如下:

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

	return dp[s.size() - 1];
}

纪念贴图:



猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/81044234