A message containing letters fromA-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 cocould be decoded"AB"
(1 2) or"L"
(12 ).
The number of ways Decoding"12"
Is 2.
Https://oj.leetcode.com/problems/decode-ways/
Idea 1: DFS.
Idea 2: DP. Like the Fibonacci series, DP [I] indicates the total number of combinations from the beginning to the I bit.
If the I-1 bit is not equal to 0, DP [I] needs to add DP [I-1.
If the I-2 bit to the I-1 bit is between 1-26, DP [I] needs to add the DP [I-2] situation.
public class Solution { // be careful of "0" "01" "100" public int numDecodings(String s) { if (s.length() == 0) return 0; int[] dp = new int[s.length() + 1]; dp[0] = 1; if (s.charAt(0) != ‘0‘) dp[1] = 1; else dp[1] = 0; for (int i = 1; i < s.length(); i++) { if (s.charAt(i) != ‘0‘) dp[i + 1] = dp[i]; if (s.charAt(i - 1) != ‘0‘ && Integer.parseInt(s.substring(i - 1, i + 1)) <= 26) dp[i + 1] += dp[i - 1]; } return dp[s.length()]; } public static void main(String[] args) { String s = "1010"; System.out.println(new Solution().numDecodings(s)); }}
View code
Refer:
Http://blog.csdn.net/u011095253/article/details/9248109
Http://blog.csdn.net/worldwindjp/article/details/19938131