【剑指offer】动态规划题目

文章目录

  • 1.连续子数组的和
  • 2.连续子数组最大和(二)
  • 3.跳台阶
  • 4.斐波那契数列
  • 5.跳台阶(二)
  • 6.矩形覆盖
  • 7.买股票问题

1.连续子数组的和

【剑指offer】动态规划题目_第1张图片

class Solution:
    def FindGreatestSumOfSubArray(self , array: List[int]) -> int:
        # write code here
        for i in range(1,len(array)):
            array[i] += max(array[i-1], 0)
        return max(array)

2.连续子数组最大和(二)

【剑指offer】动态规划题目_第2张图片

class Solution:
    def FindGreatestSumOfSubArray(self , array: List[int]) -> List[int]:
        # write code here
        left = 0
        right = 0
        bl = 0
        br = 0
        maxn = array[0]
        
        temp = [0 for i in range(len(array))]
        temp[0] = array[0]
        
        for i in range(1,len(array)):
            right += 1
            temp[i] = max(array[i], temp[i-1]+array[i])
            if temp[i-1] < 0:
                left = right
            
            if temp[i] > maxn or temp[i] == maxn and (right - left) > (br - bl):
                bl = left
                br = right
                maxn = temp[i]
                
                
        res = []
        for i in range(bl, br+1):
            res.append(array[i])
        return res

3.跳台阶

【剑指offer】动态规划题目_第3张图片

class Solution:
        
    def jumpFloor(self , number: int) -> int:
        # write code here
        res = [0 for i in range(number+1)]
        res[0] = 1
        res[1] = 1
        for i in range(2,number+1):
            res[i] = res[i-1] + res[i-2]
        return res[-1]

4.斐波那契数列

【剑指offer】动态规划题目_第4张图片

class Solution:

    def Fibonacci(self , n: int) -> int:
        # write code here
        array = [0 for i in range(n)]
        array[0], array[1] = 1, 1
        for i in range(2,n):
            array[i] = array[i-1] + array[i-2]
        return array[-1]

5.跳台阶(二)

【剑指offer】动态规划题目_第5张图片

class Solution:
    def jumpFloorII(self , number: int) -> int:
        # write code here
        res = [0 for i in range(number+1)]
        res[0], res[1] = 1, 1
        for i in range(2,number+1):
            res[i] = sum(res[0:i])
        return res[-1]

6.矩形覆盖

【剑指offer】动态规划题目_第6张图片

class Solution:
    def rectCover(self , number: int) -> int:
        # write code here
        if number == 0: return 0
        array = [0 for i in range(number+1)]
        array[0] = 1
        array[1] = 1
        for i in range(2,number+1):
            array[i] = array[i-1] + array[i-2]
        return array[-1]

7.买股票问题

【剑指offer】动态规划题目_第7张图片

class Solution:
    def maxProfit(self , prices: List[int]) -> int:
        # write code here
        cost, priced = float('+inf'), 0
        for price in prices:
            cost = min(cost, price)
            priced = max(priced, price-cost)
        return priced

你可能感兴趣的:(动态规划,算法,leetcode)