# 91. Decode Ways

{% embed url="<https://leetcode.com/problems/decode-ways/>" %}

没想到这题用`backtrack`会TLE，毕竟题目也没给数据规模，以为要求不会很高。

能做`backtrack`的题目普遍也都可以`bottom-up DP`，这题里`s[1:n+1]`的解法方法总数`dp[n]`需要靠`dp[n-2], dp[n-1]`得出。即如果`s[n-2:n]`是个10到26之间的数，就可以把`dp[n-2]`数量也加入`dp[n]`的数量。

{% tabs %}
{% tab title="Backtrack(TLE)" %}

```python
class Solution:
    def numDecodings(self, s: str) -> int:
        self.count = 0
        self.backtrack(s, 0)
        return self.count
    
    def backtrack(self, s, idx):
        if idx == len(s): 
            self.count += 1
            return
        if s[idx] != "0":
            self.backtrack(s, idx+1)
            if idx <= len(s)-2 and int(s[idx]+s[idx+1]) <= 26:
                self.backtrack(s, idx+2)
        return count
```

{% endtab %}

{% tab title="DP" %}

```python
class Solution:
    def numDecodings(self, s: str) -> int:
        dp = [0 for _ in range(len(s) + 1)] 
        
        dp[0] = 1 
        dp[1] = 0 if s[0] == "0" else 1  

        for i in range(2, len(s) + 1): 
            if 0 < int(s[i-1:i]):
                dp[i] += dp[i - 1]
            if 10 <= int(s[i-2:i]) <= 26:
                dp[i] += dp[i - 2]
                
        return dp[-1]
```

{% endtab %}
{% endtabs %}
