LeetCode 动态规划

目录

 

1.ClimbingStairs

2.Best Time to Buy and Sell Stock

3.Maximum Subarray

4.House Robber


1.ClimbingStairs

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

解决问题思路

反着考虑,有几种方案到第i阶楼梯,答案是2种:

  1. 第i-1阶楼梯经过一步
  2. 第i-2阶楼梯经过两步

假设count(i)表示到第i阶楼梯方案的个数,则count(i) = count(i-1) + count(i-2) 
第一阶是1种,第二阶是2种。代码如下:

class Solution:
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = [1,2]
        for i in range(2,n):
            count.append(count[i-1]+count[i-2])
        return count[n-1]

2.Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

允许买卖一次,要保证卖的时间晚于买的日期,第一反应找最大值和最小值,最大的早于最小的,那么就找次大和次小,这样肯定很麻烦,从这个过程已经能感受到一点动态规划的感觉。是的没错,这道题就是用动态规划,我们维持两个变量,最低买入价格和当前可达到的最高利润,从第二天开始遍历,小于最低价格那么我们更新最低价格变量,然后以这一天的价格作为卖出价格,那么利润就是卖出价格-最低价格,最次也就是0,也就是我更新了最低价格还以最低价格卖出去了,因为不能用之前的价格卖,此时利润也要相应的更新,大于保存的最大利润我们就更新,遍历完成后得到结果

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if(len(prices) <= 1):
            return 0
        buy_price = prices[0]
        max_profit = 0
        for i in range(1,len(prices)):
            buy_price = min(buy_price, prices[i])
            max_profit = max(max_profit, prices[i] - buy_price)
        return max_profit

3.Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
class Solution:
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l = len(nums)
        i = 0
        sum = 0
        MaxSum = nums[0]
        while i < l:
            sum+=nums[i]
            if sum > MaxSum:
                    MaxSum = sum
            if sum < 0:
                sum = 0
            i+=1
        return MaxSum

4.House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.
Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
             Total amount you can rob = 2 + 9 + 1 = 12.
class Solution:
    def rob(self,nums):
        r ={}
        if len(nums)==0:
            return 0
        if len(nums)==1:
            return nums[0]
        if len(nums)==2:
            return max(nums[0],nums[1])
        else:
            r[0] = nums[0]
            r[1] =max(nums[0],nums[1])
            for i in range(2,len(nums)):
                r[i] = max(r[i-1],r[i-2]+nums[i])
        return r[len(nums)-1]
        

猜你喜欢

转载自blog.csdn.net/yanyiting666/article/details/88934989