// 前端算法js:跳格子有多少种走法-斐波拉切数列
function totalNum(num) {
if (num == 1) {
return 1;
}
if (num == 2) {
return 2;
}
if (num > 2) {
return totalNum(num - 1) + totalNum(num - 2); // 递归
}
}
console.log(totalNum(2));
console.log(totalNum(3));
console.log(totalNum(40));
function gh(num) {
let arr = [0, 1, 2];
for (let i = 3; i <= num; i++) {
arr[i] = arr[i - 1] + arr[i - 2]; // 动态规划
}
return arr[num];
}
console.log(gh(2)); // 2
console.log(gh(3)); // 3
console.log(gh(40)); // 165580141
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)