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?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
题目要求
- 假定你正在爬梯子,梯子有n级,假定你每次可以爬一级梯子或者两级梯子,求你爬上n级梯子有多少种爬法。
解题思路
采用动态规划法来解,动态规划法的核心是状态和状态转移方程,在这里我们设还剩爬n级梯子可能的方法数是stairs[n],那么从爬到n级有两种方法,要么从n-1级爬1级,要么从n-2级爬两级。于是状态转移方程可以写成,stairs[n]=stairs[n-1]+stairs[n-2]。
时间复杂度O(n) 超过100%的java提交
class Solution {
public int maxSubArray(int[] nums) {
int l = 0,r = nums.length;
return recursive(nums,l,r);
}
private int recursive(int[] nums,int l,int r){
if(l+1==r) return nums[l];
int middle = (l+r)/2;
int lval = recursive(nums,l,middle);
int rval = recursive(nums,middle,r);
// 合并中间的值
int lspread=2,rspread=1,maxl = nums[middle-1],maxr=nums[middle];
int templ=maxl,tempr=maxr;
while(middle-lspread>=l){
templ+=nums[middle-lspread];
maxl = Math.max(maxl,templ);
lspread++;
}
while(middle+rspread<r){
tempr+=nums[middle+rspread];
maxr=Math.max(maxr,tempr);
rspread++;
}
return Math.max(maxr+maxl,Math.max(lval,rval));
}
}