Review an answer - Decode Ways

前端 未结 7 1229
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 19:36

I\'m trying to solve a question and my question here is why doesn\'t my solution work?. Here\'s the question and below\'s the answer.

Question taken fr

相关标签:
7条回答
  • 2021-01-31 20:38

    Here is an O(N) C++ DP implementation.

    int numDecodings(string s) {
    
        if(s[0] == '0') return 0; // Invalid Input
            
        int n = s.length();
    
        // dp[i] denotes the number of ways to decode the string of length 0 to i
        vector<int> dp(n+1, 0);
            
        // base case : string of 0 or 1 characters will have only 1 way to decode
        dp[0] = dp[1] = 1; 
            
        for(int i = 2; i <= n; i++) {
            // considering the previous number
            if(s[i-1] > '0') dp[i] += dp[i-1];
            // considering the previous two numbers
            if(s[i-2] == '1' || (s[i-2] == '2' && s[i-1] < '7')) dp[i] += dp[i-2];
        }
            
        return dp[n];
    }
    
    0 讨论(0)
提交回复
热议问题