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?
这个题可以运用DP方法来解决,在我们要上到第n阶楼梯时,可以往前考虑一步,第一种情况是在第n-1阶时上一步,第二种情况是在第n-2阶时上两步。在只有一阶楼梯时有一种上法,两阶楼梯时有两种上法。可以得到公式S[n]=S[n-1]+S[n-2],S[2]=2,S[1]=1。
class Solution {
public:
int climbStairs(int n) {
if(n<3)
return n;
else
{
vector<int> ways(n);
ways[0]=1;
ways[1]=2;
for(int i=2;i<n;i++)
ways[i]=ways[i-1]+ways[i-2];
return ways[n-1];
}
}
};
Maximum Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4]
,
the contiguous subarray [4,-1,2,1]
has the largest sum = 6
.
在寻找子列最大值的问题中同样可以用DP的方法实现。在当前位置的大小可以通过比较nums[i]与前一个位置的最大值加上该位置的值,即big[i]+nums[i]。用一个max记录最大值并不断更新即可。
class Solution {
public:
int maxSubArray(vector<int>& nums)
{
if(nums.size()<1)return 0;
int m=nums[0];
vector<int> big(nums.size());
big[0]=nums[0];
for(int i=1;i<nums.size();i++)
{
big[i]=max(nums[i],big[i-1]+nums[i]);
if(big[i]>m)
m=big[i];
}
return m;
}
};