1. 爬楼梯
1.1 一般方法
public class Solution {
public int ClimbStairs(int n) {
int prev = 1, curr = 1;
for(int i = 2; i <= n; i ++){
var next = curr + prev;
prev = curr;
curr = next;
}
return curr;
}
}
”斐波那契“,f(n) = f(n - 1) + f(n - 2)。
1.2 动态规划
public class Solution {
public int ClimbStairs(int n) {
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
for(int i = 2; i <= n; i++)
{
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
}
1.3 递归
public class Solution {
public int ClimbStairs(int n) {
if(n == 1) return 1;
if(n == 2) return 2;
return ClimbStairs(n-1) + ClimbStairs(n-2);
}
}
这种直接递归因为进行了太多重复计算,故使用字典保存已经计算过的结果来减少重复计算。
public class Solution {
Dictionary<int, int> dict = new Dictionary<int, int>();
public int ClimbStairs(int n)
{
if (n == 1) return 1;
if (n == 2) return 2;
if (dict.ContainsKey(n)) return dict[n];
else
{
dict[n] = ClimbStairs(n - 1) + ClimbStairs(n - 2);
return dict[n];
}
}
}
1.4 矩阵快速幂
利用快速幂求二维矩阵n次方的方法如下
// 计算矩阵的幂
public int[][] Pow(int[][] matrix, int n)
{
// 初始化单位矩阵
int[][] res = new int[2][];
res[0] = new int[]{1, 0};
res[1] = new int[]{0, 1};
//快速幂的思想
while(n > 0)
{
if(n % 2 == 1)
{
res = Multiply(matrix, res);
}
n /= 2;
matrix = Multiply(matrix, matrix);
}
return res;
}
// 二维矩阵相乘
public int[][] Multiply(int[][] a, int[][] b)
{
int[][] res = new int[2][];
for (int i = 0; i < 2; i++)
{
res[i] = new int[2];
for (int j = 0; j < 2; j++)
{
res[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j];
}
}
return res;
}
题目解法
public class Solution {
public int ClimbStairs(int n) {
int[][] matrix = {
new int[]{1, 1},
new int[]{1, 0}
};
int[][] res = Pow(matrix, n);
return res[0][0];
}
}
``