8.22 Leetcode refresh task2 dynamic programming (9-code knocking team-QQ)

  1. The longest palindrome substring
    Given a string s, find the longest palindrome substring in s. You can assume that the maximum length of s is 1000. The palindrome substring is the same from left to right and right to left.
    Dynamic programming
class Solution:
    def longestPalindrome(self, s: str) -> str:
        n = len(s)
        dp = [[False] * n for c in range(n)]
        res = ""
        for l in range(n):
            for i in range(n):
                j = i + l
                if j >= len(s):
                    break
                if l == 0:
                    dp[i][j] = True
                elif l == 1:
                    dp[i][j] = (s[i] == s[j])
                else:
                    dp[i][j] = (dp[i + 1][j - 1] and s[i] == s[j])
                if dp[i][j] and l + 1 > len(res):
                    res = s[i:j+1]
        return res
a=Solution()
print(a.longestPalindrome("baaba"))

Central diffusion method:

class Solution:
    def expandAroundCenter(self, s, left, right):
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        return left + 1, right - 1

    def longestPalindrome(self, s: str) -> str:
        start, end = 0, 0
        for i in range(len(s)):
            left1, right1 = self.expandAroundCenter(s, i, i)
            left2, right2 = self.expandAroundCenter(s, i, i + 1)
            if right1 - left1 > end - start:
                start, end = left1, right1
            if right2 - left2 > end - start:
                start, end = left2, right2
        return s[start: end + 1]
a=Solution()
print(a.longestPalindrome("bababac"))
  1. Edit distance
    Given two words word1 and word2, please calculate the minimum number of operations used to convert word1 to word2.
    You can perform the following three operations on a word:
    insert a character,
    delete a character,
    replace a character
    Method one: dynamic programming:
class Solution:
    def minDistance(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        n = len(word1)
        m = len(word2)

        # 有一个字符串为空串
        if n * m == 0:
            return n + m

        # DP 数组
        D = [[0] * (m + 1) for _ in range(n + 1)]

        # 边界状态初始化
        for i in range(n + 1):
            D[i][0] = i
        for j in range(m + 1):
            D[0][j] = j

        # 计算所有 DP 值
        for i in range(1, n + 1):
            for j in range(1, m + 1):
                left = D[i - 1][j] + 1
                down = D[i][j - 1] + 1
                left_down = D[i - 1][j - 1]
                if word1[i - 1] != word2[j - 1]:
                    left_down += 1
                D[i][j] = min(left, down, left_down)

        return D[n][m]
a=Solution()
print(a.minDistance(word1 = "intention", word2 = "execution"))

198.
House Robbery You are a professional thief who plans to steal houses along the street. There is a certain amount of cash hidden in each room. The only constraint that affects your theft is that the adjacent houses are equipped with interconnected anti-theft systems. If two adjacent houses are broken into by a thief at the same night, the system will automatically alarm .

Given an array of non-negative integers representing the amount of money stored in each house, calculate the maximum amount that can be stolen overnight without touching the alarm device.

Dynamic programming method:

class Solution:
    def rob(self, nums: list) -> int:
        if not nums:
            return 0

        size = len(nums)
        if size == 1:
            return nums[0]

        first, second = nums[0], max(nums[0], nums[1])
        for i in range(2, size):
            first, second = second, max(first + nums[i], second)

        return second
a=Solution()
print(a.rob([2,7,9,3,1]))
#结果为12

213.
House Robbery 2 You are a professional thief. You plan to steal houses along the street. There is a certain amount of cash hidden in each house. All houses in this place are in a circle, which means that the first house and the last house are next to each other. At the same time, adjacent houses are equipped with interconnected anti-theft systems. If two adjacent houses are broken into by a thief at the same night, the system will automatically alarm.
Given an array of non-negative integers representing the amount of storage in each house, calculate the highest amount you can steal without triggering the alarm device.

class Solution:
    def rob(self, nums: list) -> int:
        if not nums:
            return 0

        size = len(nums)
        if size == 1:
            return nums[0]

        first, second = nums[0], max(nums[0], nums[1])
        for i in range(2, size):
            first, second = second, max(first + nums[i], second)

        return second
    def circle(self,nums):
        a=nums[1:len(nums)]
        b=nums[0:len(nums)-1]
        result=max(self.rob(a),self.rob(b))
        return result
c=Solution()
print(c.circle([1,2,3,1]))
#4

Method 2: Use a two-dimensional array to record whether the first room was stolen, and analyze the last room separately:

class Solution:
  def rob(self,nums):
    n = len(nums)
    if n < 1:
      return 0
    if 1<=n < 4:
     return max(nums[0],nums[1],nums[2])
    dp = [[0] * 2 for i in range(n)]
    dp[0][0] = 0 #没偷第0家时,偷到前0家的最大金额为0
    dp[0][1] = nums[0] # 有偷第0家时,偷到前0家的最大金额为nums[0]
    dp[1][1] = nums[0]#有偷第0家时,偷到前1家的最大金额为nums[0]
    dp[1][0] = nums[1] # 没偷第0家时,偷到前1家的最大金额为nums[1]
    for i in range(2,n):
      if i != n - 1:
        # 如果不是偷最后一家,分有偷第0家和不偷第0家两条路线进行状态转移
        dp[i][0] = max(dp[i-1][0], dp[i-2][0] + nums[i])
        dp[i][1] = max(dp[i-1][1], dp[i-2][1] + nums[i])
      else:
         # 偷最后一家时, 如果没偷过第0家,可以直接选择偷或者不偷
        dp[i][0] = max(dp[i-1][0], dp[i-2][0] + nums[i])
         # 如果已经偷过第0家,只能选择不偷
        dp[i][1] = dp[i-1][1]

        # 返回两种偷法中金额较大的一种
    return max(dp[n - 1][0], dp[n - 1][1])
a=Solution()
print(a.rob([1,2,3,1]))
#4

how are you:

class Solution:
    def rob(self, nums: list) -> int:
        if not nums or len(nums) == 1:
            return sum(nums)
        a, b, c, d = 0, 0, 0, nums[0]
        for i in nums[1: -1]:
            a, b, c, d = b, max(b, a+i), d, max(d, c+i)
        return max(b, a+nums[-1], d)
a=Solution()
print(a.rob([3,2,3]))
#3
  1. Longest palindrome subsequence
    Given a string s, find the longest palindrome subsequence and return the length of the sequence. It can be assumed that the maximum length of s is 1000.

Dynamic programming:

class Solution:
    def longest(self, s:str):
        n = len(s)
        dp = [[0] * n for k in range(n)]
        for i in range(n-1,-1,-1):
            dp[i][i] = 1
            for j in range(i+1,n):
                if s[i]==s[j]:
                    dp[i][j] = dp[i + 1][j - 1] + 2
                else:
                    dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
        return dp[0][n - 1]
a=Solution()
print(a.longest("bbbab"))
#4 即bbbb

This solution calculates the value of the array from bottom to top, from left to right, and
finds the largest palindrome from the middle line diagonally. It can be
674. The longest continuous increasing sequence
Given an unsorted integer array, find the longest and continuous The increasing sequence of and returns the length of the sequence.
Violent solution:

class Solution:
    def longest(self, nums:list):
        s=0
        n=len(nums)
        if n==0:
            return 0
        i=j=0
        for k in range(n-1):
            if nums[k]<nums[k+1]:
               j=k+1
            else:
               i=k+1
               j=k+1
            s=max(s,j-i+1)
        return s
a=Solution()
print(a.longest([1,3,5,4,7]))
#3   即【1,3,5】

Dynamic programming:

class Solution:
    def longest(self, nums:list):
        n=len(nums)
        if n==0:  
           return 0
        dp = [0]*n
        dp[0]=1
        for i in range(1,n):
            if nums[i]>nums[i-1]:
                dp[i]=dp[i-1]+1
            else:
                dp[i]=1
        return max(dp)
a=Solution()
print(a.longest([2,2,2,2,2]))

Or initialize the array to 1 to be more refined:

class Solution:
    def longest(self, nums:list):
        n=len(nums)
        if n==0:
            return 0
        dp = [1]*n
        for i in range(1,n):
            if nums[i]>nums[i-1]:
                dp[i]=dp[i-1]+1
        return max(dp)
a=Solution()
print(a.longest([1,3,5,4,7]))

Guess you like

Origin blog.csdn.net/m0_45672993/article/details/108128741