标签:style blog http color os art
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.
https://oj.leetcode.com/problems/decode-ways/
思路1:dfs。
思路2:dp。类似斐波那契数列,dp[i]表示从头到i位共有多少中组合。
如果i-1位不等于0,则dp[i]需要加上dp[i-1]的情况。
如果i-2位到i-1位在1-26之间,则dp[i]需要加上dp[i-2]情况。
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)); } }
参考:
http://blog.csdn.net/u011095253/article/details/9248109
http://blog.csdn.net/worldwindjp/article/details/19938131
[leetcode] Decode Ways,布布扣,bubuko.com
标签:style blog http color os art
原文地址:http://www.cnblogs.com/jdflyfly/p/3819308.html