91. Decode Ways

来源:互联网 发布:意大利2 0西班牙知乎 编辑:程序博客网 时间:2024/05/10 22:39

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.



The naive approach is use dfs:

suppose we have 1123456

the answer should be f(123456) + f(23456)

To improve the performance we could use memory to avoid repeating computation.


Code:

public class Solution {    public int numDecodings(String s) {        // start, end        if(s.equals("")) return 0;        HashMap<Integer,Integer> hm = new HashMap();        hm.put(s.length(),1);        return search(0,s,hm);    }        public int search(int start, String s, HashMap<Integer,Integer> hm){        if(hm.containsKey(start)){            return hm.get(start);        }                int i = s.charAt(start) - '0';        if(i == 0){            hm.put(start, 0);            return 0;        }        int ans = search(start + 1, s, hm);        if(start + 1 < s.length()){            i = i * 10 + s.charAt(start + 1) - '0';            if(i <= 26){                ans += search(start + 2, s, hm);            }        }        hm.put(start, ans);        return ans;    }}

The is actually the same using DP:

if(s[i] == '0') dp[i] = 0;

else{

DP[i] = DP[i + 1] + ((s[i]*10 + s[i + 1] <= 26) ? DP[i + 2] : 0)



0 0