算法设计与应用基础-第十二周

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;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值