题目
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
- 1 阶 + 1 阶
- 2 阶
示例 2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
- 1 阶 + 1 阶 + 1 阶
- 1 阶 + 2 阶
- 2 阶 + 1 阶
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/climbing-stairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
class Solution {
public int[][] pow(int[][] a,int n){
int[][] res={{1,0},{0,1}};
while(n>0){
if((n&1)==1){
res = multiply(res,a);
}
n>>=1;
a=multiply(a,a);
}
return res;
}
public int[][] multiply(int[][] a,int[][] b){
int[][] res=new int[2][2];
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
for(int k=0;k<2;k++){
res[i][j]+=a[i][k]*b[k][j];
}
}
}
return res;
}
public int climbStairs(int n) {
int[][] q={{1,1},{1,0}};
int[][] ans = pow(q,n);
return ans[0][0];
}
}