爬楼梯
/**
* 时间复杂度O(2^n)
*/
const climbStairsByRecursion = (n) => { if(n === 1) return 1 if(n === 2) return 2 return climbStairsByRecursion(n - 1) + climbStairsByRecursion(n - 2) }
/**
* 记忆化斐波那契
*/
const climbStairsByMemory = (n) => { const memory = [1,1] const fibonacci = (n) => { if(memory[n]) return memory[n] return memory[n] = fibonacci(n - 1, memory) + fibonacci(n - 2, memory) } return fibonacci }
/**
* 动态规划
* 时间复杂度O(n)
* 空间复杂度O(n)
*/
const climbStairsByDynamic = (n) => { const arr = [0,1,2] if(n < 3){ return arr[n] } for(let i = 3; i <= n; i++){ arr[i] = arr[i - 1] + arr[i - 2] } return arr[n] }
/**
* 斐波那契
* 时间复杂度O(n)
* 空间复杂度O(1)
*/
const climbStairsByFibonacci = (n) => { let x = 1,y = 1 while(--n > 0){ y = x + y x = y - x } return y }
以自己现在的努力程度,还没有资格和别人拼天赋