题意:

image.png

解题思路:

  1. 思路:
  2. 状态定义:f[i] 表示上 i 级台阶的方案数
  3. 转移方程:枚举最后一步是上1级台阶,还是上2级台阶 =》 f(n) = f(n-1) + f(n-2)
  4. 复杂度分析:递推状态数 O(n),转移时间复杂度是 O(1),所以总时间复杂度是 O(n)

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer $n
  4. * @return Integer
  5. */
  6. function climbStairs1($n) {
  7. if ($n < 2) {
  8. return 1;
  9. }
  10. return $this->climbStairs($n - 1) + $this->climbStairs($n -2);
  11. }
  12. function climbStairs($n) {
  13. return $this->climstairDp1($n);
  14. //return $this->climbstairFab($n);
  15. //return $this->climbStairDp($n);
  16. //return $this->climbStairsDfs(0, $n);
  17. //$memo = array_fill(0, $n + 1, 0);
  18. //return $this->climbStairsDfsMemo(0, $n, $memo);
  19. }
  20. /*
  21. 楼梯数:3:
  22. f[i-1]: 2 -> 1 //在第 (i-1)(i−1) 阶后向上爬一阶 2 + 1
  23. f[i-2]: 1 => 2 //在第 (i−2) 阶后向上爬 2 阶, (1+1+1) (1+2)
  24. */
  25. function climbStairDp($n) {
  26. if ($n == 1) return 1;
  27. $dp = array_fill(0, $n + 1, 0);
  28. $dp[1] = 1; $dp[2] = 2;
  29. for ($i = 3; $i <= $n; $i++) {
  30. $dp[$i] = $dp[$i - 1] + $dp[$i - 2];
  31. }
  32. return $dp[$n];
  33. }
  34. //因为后面的只会依赖前面2个值 O(n)
  35. function climstairDp1($n) {
  36. if ($n == 1) return 1;
  37. if ($n == 2) return 2;
  38. $first = 1;
  39. $second = 2;
  40. for ($i = 3; $i <= $n; $i++) {
  41. $third = $first + $second;
  42. $first = $second;
  43. $second = $third;
  44. }
  45. return $second;
  46. }
  47. //斐波那契数(Time Limit Exceeded)
  48. function climbstairFab($n) {
  49. if ($n < 2) return 1;
  50. return $this->climbstairFab($n - 1) + $this->climbstairFab($n - 2);
  51. }
  52. //O(2^n) TLE
  53. function climbStairsDfs($i, $n) {
  54. if ($i > $n) return 0;
  55. if ($i == $n) return 1;
  56. return $this->climbStairsDfs($i + 1, $n) + $this->climbStairsDfs($i + 2, $n);
  57. }
  58. //O(n)树形递归的大小可以达到 n。 //TLE
  59. function climbStairsDfsMemo($i, $n, $memo) {
  60. if ($i > $n) return 0;
  61. if ($i == $n) return 1;
  62. if ($memo[$i] > 0) return $memo[$i];
  63. $memo[$i] = $this->climbStairsDfsMemo($i + 1, $n, $memo) + $this->climbStairsDfsMemo($i + 2, $n, $memo);
  64. return $memo[$i];
  65. }
  66. }

GO代码实现:

  1. func climbStairs(n int) int {
  2. if n == 1 {
  3. return 1
  4. }
  5. if n == 2 {
  6. return 2
  7. }
  8. return climbStairs(n-2) + climbStairs(n-1)
  9. }
  10. func climbStairs1(n int) int {
  11. var result = []int{0, 1, 2}
  12. for i := 3; i <= n; i++ {
  13. result = append(result, result[i-1] + result[i-2])
  14. }
  15. return result[n]
  16. }
  17. func climbStairs2(n int) int {
  18. var first, second = 1, 2
  19. if n == 1 {
  20. return 1
  21. }
  22. if n == 2 {
  23. return 2
  24. }
  25. for i := 3; i <= n; i++ {
  26. first, second = second, first + second
  27. }
  28. return second
  29. }