本文主要是介绍leetcode70: Climbing Stairs,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
要求:You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
注意:基本动态规划问题,只要写出状态转移方程就可以了。当到了第i个阶梯时,它之前的状态只有两种:i-1或i-2。f(i)表示到第i个阶梯的方法总数,那么有:f(i) = f(i-1) + f(i-2),因此,只要用一个数组来保存每次的状态就可以了(也可以用两个变量保存,空间复杂度低)
public int climbStairs(int n) {if (n <= 1)return 1;int[] k = new int[n + 1];k[1] = 1;k[2] = 2;for (int i = 3; i <= n; i++) {k[i] = k[i - 1] + k[i - 2];}return k[n];}
这篇关于leetcode70: Climbing Stairs的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!