LeetCode - 70.Climbing Stair
link: https://leetcode.com/problems/climbing-stairs/description/
题目
You are climbing a staircase. It takes n
steps to reach
the top.
Each time you can either climb 1
or 2
steps. In how many distinct ways can you climb to the top?
Example 1:
1 | Input: n = 2 |
Example 2:
1 | Input: n = 3 |
Constraints:
1 <= n <= 45
问题描述
爬楼梯,一次可以爬1层或2层,问到n层有几种方法
问题分析
很显然可以得到通项公式 f(n)=f(n−1)+f(n−2)
f(1)=1
方法一:动态规划
这种方法没啥好说的,最多就是常数空间有点用
1 | func climbStairs(n int) int { |
方法二:矩阵计算
可以写作矩阵乘法 [f(n+1)f(n)]=[1110][f(n)f(n−1)]=[1110]n[f(1)f(0)]
矩阵快速幂
可以参考普通快速幂的方法
1 | type matrix [2][2]int |
特征值分解
对 A=[1110]
A是实对称矩阵,假设存在可逆矩阵P
和对角矩阵D
使得
A=PDP−1
得特征向量 v1=[1+√521]
得特征向量 v2=[1−√521]
D=[1+√52001−√52]
则 An=PDnP−1=[1+√521−√5211][1+√52001−√52]n[1+√521−√5211]−1=1√5[(1+√52)n+1−(1−√52)n+1(1+√52)n−(1−√52)n(1+√52)n−(1−√52)n(1+√52)n−1−(1−√52)n−1]
则 f(n)=((1+√52)n+1−(1−√52)n+1)∗1√5
1 | import "math" |
方法二:递推数列的通项公式
根据f(n)=f(n−1)+f(n−2)得到特征方程 x2=x+1
C2=−1√5
因此通项公式 f(n)=((1+√52)n−(1−√52)n)∗1√5