const fibs = n => { const dp = [1, 1]; if (n === 1 || n === 2) { return1; } for (let i = 2; i < n; i++) { dp[i] = dp[i - 1] + dp[i - 2]; } return dp[n - 1]; };
第四种,中间值法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
const fibs = n => { if (n === 1 || n === 2) { return1; } let ppre = 1; let pre = 1; let tmp; for (let i = 2; i < n; i++) { tmp = ppre + pre; ppre = pre; pre = tmp; } return tmp; };
第五种,尾递归
1 2 3 4 5 6 7 8
const fibs = n => fibsTailRecursion(1, 1, n);
const fibsTailRecursion = (ppre, pre, n) => { if (n === 1) { return ppre; } return fibsTailRecursion(pre, pre + ppre, n - 1); };