Leetcode 91
题面
- Decode Ways
 
Medium
A message containing letters from A-Z is being encoded to numbers using the following mapping:
1  | 'A' -> 1  | 
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
1  | Input: "12"  | 
Example 2:
1  | Input: "226"  | 
思路
这个题面比较直白,一看就知道用DP来做了(即分解成子问题),很明显是
- 读末尾的1位+剩下所有可能的组合
 - 读末尾的2位+剩下所有可能的组合
 
这样。
然后起枪,被秒了,有什么好说的。
为什么呢?因为字符串里面并不guarantee没有0,而0是不可解的,这算是一个小坑,而我们应该做的呢,是把DP的过程想象成一个二叉树,每一个节点的值等于它所有后代的值的和,如果一个后代遇到当前不可解的情况,就直接返回0。
code
1  | /**  |