https://leetcode-cn.com/problems/decode-ways/

动态规划

从左到右的尝试模型

  1. public int numDecodings(String s) {
  2. if (s == null || s.length() == 0) {
  3. return 0;
  4. }
  5. char[] str = s.toCharArray();
  6. return process(str, 0);
  7. }
  8. // 潜台词:str[0...index-1]已经转化完了,不用操心了
  9. // str[index....] 能转出多少有效的,返回方法数
  10. private int process(char[] str, int index) {
  11. if (index == str.length) {
  12. return 1;
  13. }
  14. if (str[index] == '0') {
  15. return 0;
  16. }
  17. int ways = process(str, index + 1);
  18. if (index + 1 == str.length) {
  19. return ways;
  20. }
  21. int num = (str[index] - '0') * 10 + (str[index + 1] - '0');
  22. if (num <= 26) {
  23. ways += process(str, index + 2);
  24. }
  25. return ways;
  26. }
  1. // 动态规划
  2. public int numDecodings2(String s) {
  3. if (s == null || s.length() == 0) {
  4. return 0;
  5. }
  6. int N = s.length();
  7. int[] dp = new int[N + 1];
  8. char[] str = s.toCharArray();
  9. dp[N] = 1;
  10. for (int i = N - 1; i >= 0; i--) {
  11. if (str[i] != '0') {
  12. dp[i] = dp[i + 1];
  13. if (i + 1 == str.length) {
  14. continue;
  15. } else {
  16. int num = (str[i] - '0') * 10 + (str[i + 1] - '0');
  17. if (num <= 26) {
  18. dp[i] += dp[i + 2];
  19. }
  20. }
  21. }
  22. }
  23. return dp[0];
  24. }