leetcode 70. 爬楼梯
作者:互联网
深度优先搜索方法的实现:出现超时。
/** * @param {number} n * @return {number} */ var cnt=0; var deepSearch = function(curLevel,n){ if(curLevel >= n){ if(curLevel==n){ cnt++; } return; }else{ let newLevel = curLevel+1; deepSearch(newLevel,n); newLevel = curLevel+2; deepSearch(newLevel,n); } } var climbStairs = function(n) { cnt = 0; deepSearch(0,n,cnt); return cnt; };
递归方式实现,依然超时:
/** * @param {number} n * @return {number} */ var climbStairs = function(n) { if(n==1){ return 1 }else if(n==2){ return 2 }else{ return climbStairs(n-1)+climbStairs(n-2); } };
采取状态压缩的策略,只需要记录三个变量即可:
/** * @param {number} n * @return {number} */ var climbStairs = function(n) { let a = 1;//0 let b = 1;//1 if(n==0||n==1){ return 1; } else { for(let i = 2;i<=n;i++){ res = a+b; a = b; b = res; } return b; } };
标签:cnt,return,curLevel,number,climbStairs,70,var,爬楼梯,leetcode 来源: https://www.cnblogs.com/KYSpring/p/15325490.html