题意:

image.png

解题思路:

  1. 思路:
  2. 状态定义:dp[i]代表以s[i]结尾的字符串的解码总数;
  3. 初始化:dp[0] = 1
  4. 状态转移:
  5. 1. s[i-1] != '0'时, s[i-1]在[1-9]中,那么可以单独把它解码成一个数字,方案数
  6. dp[i] = dp[i-1],即形成一种方案;
  7. 2. s[i-2] == '1' || s[i-2] == '2' && s[i-1] <= '6'时,即是s[i-2],s[i-1]
  8. 能组成一个两位数的编码时[10-26],那么可以把这两位解码成一个数字,即dp[i] += dp[i-2]
  9. 3. 最后返回dp[n]

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param String $s
  4. * @return Integer
  5. */
  6. function numDecodings($s) {
  7. $len = strlen($s);
  8. $dp = array_fill(0, $len + 1, 0);
  9. $dp[0] = 1;
  10. $dp[1] = $s[0] != '0' ? 1 : 0;
  11. for ($i = 2; $i <= $len; $i++) {
  12. $first = substr($s, $i - 1, 1);
  13. $second = substr($s, $i - 2, 2);
  14. if ($first >= 1 && $first <= 9) $dp[$i] += $dp[$i - 1];
  15. if ($second >= 10 && $second <= 26) $dp[$i] += $dp[$i - 2];
  16. }
  17. return $dp[$len];
  18. }
  19. function numDecodingsDp($s) {
  20. $len = strlen($s);
  21. $dp = array_fill(0, $len + 1, 0);
  22. $dp[0] = 1;
  23. $dp[1] = $s[0] != '0' ? 1 : 0;
  24. for ($i = 2; $i <= $len; $i++) {
  25. if ($s[$i - 1] != '0') $dp[$i] += $dp[$i - 1];
  26. if ($this->isValidTwoDigit($s[$i - 2], $s[$i - 1])) $dp[$i] += $dp[$i - 2];
  27. }
  28. return $dp[$len];
  29. }
  30. function isValidTwoDigit($a, $b) {
  31. return ($a == '1' && $b <= '9') || ($a == '2' && $b <= '6');
  32. }
  33. }
  1. class Solution {
  2. function numDecodings($s) {
  3. return $this->decode($s, 0);
  4. }
  5. function decode($c, $i) {
  6. if ($i == strlen($c)) return 1;
  7. if ($i > strlen($c)) return 0;
  8. $num = 0;
  9. if ($c[$i] != '0') $num += $this->decode($c, $i + 1);
  10. if ($i + 1 < strlen($c) && $this->isValidTwoDigit($c[$i], $c[$i + 1]))
  11. $num += $this->decode($c, $i + 2);
  12. return $num;
  13. }
  14. function isValidTwoDigit($a, $b) {
  15. return ($a == '1' && $b <= '9') || ($a == '2' && $b <= '6');
  16. }
  17. }

GO代码实现:

  1. func numDecodings(s string) int {
  2. n := len(s)
  3. if n == 0 || s[0] == '0' {
  4. return 0
  5. }
  6. dp := make([]int, n+1)
  7. dp[0], dp[1] = 1, 1
  8. for i := 2; i <= n; i++ {
  9. if s[i - 1] != '0' {
  10. dp[i] = dp[i - 1]
  11. }
  12. if s[i - 2] == '1' || s[i - 2] == '2' && s[i - 1] <= '6' {
  13. dp[i] += dp[i - 2]
  14. }
  15. }
  16. return dp[n]
  17. }