91. Decode Ways

DFS + memo

T: O(2^n) => O(n)

S: O(n)

class Solution {
    
    public int numDecodings(String s) {

        return dfs(0, s, new Integer[s.length()+1]);
    }
    private int dfs(int i, String s, Integer[] memo) {
        // we are counting how many ways there are to decode the entire string. 
        // We only increase the count by 1 when the entire string is decoded (i.e. reached the end)
        if (i == s.length()) {  //base case => 成立就 1 way
            return 1;
        }
        if (s.charAt(i) == '0') {
            return 0;
        }
        if (memo[i] != null) {
            return memo[i];
        }
        // 這題就是有兩個分支, 一位 or 2位, 但要符合規則
        int way1 = dfs(i+1, s, memo); // 選多一位的分支
        int way2 = 0;
        // 2 digits, 不越界, 選多2位的分支
        if (i < s.length() -1 && Integer.parseInt(s.substring(i, i+2)) <= 26) {
            way2 = dfs(i+2, s, memo);
        }
        memo[i] = way1 + way2;
        return memo[i];
    }
}

/*
  12
  / \
1   12 
/
2

brute force
O(2^n)


06
/
x

   121 
   /\
 1   12 \
 /\      1  => so when to the end, there 1 way 
2  21 => but if over 26, it's x
/     => so when to the end, there 1 way 
1 => so when to the end, there 1 way

 can't start with 0

first digit
1-9

first digit 1 , secodn 0~9
            2 , second 0~6
            
so subproblem, because most to 26 , 是兩位數所以不是用一位, 就是兩位

[1] 21 =>  dp[i+1]
or 
[12] 1 =>. dp[i+2]
dp[i] = dp[i+1] + dp[i+2]

i+1 位的 ways + i+2 位的 ways





*/

DP

top down

O(n)

O(n)

buttom up DP

dp => buttom up, so dp[i] = dp[i -xx

dfs+memo => top down, so result = dfs(i+1)....

new comment

use char

Last updated

Was this helpful?