当前位置:网站首页>break algorithm---dynamic planning(dp-arr)

break algorithm---dynamic planning(dp-arr)

2022-06-13 11:39:00 Nonxinyou



Statement :
The algorithm is based on https://labuladong.github.io/
python Language implementation



300.longest-increasing-subsequence
354. Russian Doll Envelopes
1143. Longest Common Subsequence
1425. Constrained Subsequence Sum







300.longest-increasing-subsequence

from typing import List


class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        # dp[i]: The value is nums[i] At the end of the LIS value 
        #  Find the number that ends with each number in the array LIS, The final answer is the biggest one 
        dp = [1] * len(nums)
        for i in range(0, len(nums), 1):
            for j in range(0, i, 1):
                if nums[j] < nums[i]:
                    dp[i] = max(dp[i], dp[j] + 1)

        res = 0
        for i in range(len(nums)):
            res = max(res, dp[i])

        return res


def main():
    # Input: nums = [10,9,2,5,3,7,101,18]
    # Output: 4
    # Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
    solution1 = Solution()
    print(solution1.lengthOfLIS(nums=[10, 9, 2, 5, 3, 7, 101, 18]))

    # Input: nums = [0,1,0,3,2,3]
    # Output: 4
    solution2 = Solution()
    print(solution2.lengthOfLIS(nums=[0, 1, 0, 3, 2, 3]))

    # Input: nums = [7,7,7,7,7,7,7]
    # Output: 1
    solution3 = Solution()
    print(solution3.lengthOfLIS(nums=[7, 7, 7, 7, 7, 7, 7]))


if __name__ == '__main__':
    main()




354. Russian Doll Envelopes

from typing import List
from bisect import *


class SolutionTimeLimitExceeded:
    def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
        w = len(envelopes)
        #  By width w Ascending order , If the width is the same , According to the height h Descending order : Put the sorted h As an array , Calculate on this array LIS The length of is the final answer .
        envelopes.sort(key=lambda x: (x[0], -x[1]))

        #  Look for the height array LIS
        height = [0] * w
        for i in range(w):
            height[i] = envelopes[i][1]

        return self.lengthOfLIS(height)

    def lengthOfLIS(self, nums: List[int]) -> int:
        # dp[i]: The value is nums[i] At the end of the LIS value 
        #  Find the number that ends with each number in the array LIS, The final answer is the biggest one 
        dp = [1] * len(nums)
        for i in range(len(nums)):
            for j in range(0, i):
                if nums[j] < nums[i]:
                    dp[i] = max(dp[i], dp[j] + 1)

        res = 1
        for i in range(len(nums)):
            res = max(res, dp[i])

        return res


class Solution:
    def maxEnvelopes(self, E: List[List[int]]) -> int:
        E.sort(key=lambda x: (x[0], -x[1]))
        dp = []
        for _, height in E:
            left = bisect_left(dp, height)
            if left == len(dp):
                dp.append(height)
            else:
                dp[left] = height
        return len(dp)


def main():
    # Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
    # Output: 3
    # Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
    solution1 = Solution()
    print(solution1.maxEnvelopes([[5, 4], [6, 4], [6, 7], [2, 3]]))

    # Input: envelopes = [[1,1],[1,1],[1,1]]
    # Output: 1
    solution2 = Solution()
    print(solution2.maxEnvelopes([[1, 1], [1, 1], [1, 1]]))

    # Input: [[1,15],[7,18],[7,6],[7,100],[2,200],[17,30],[17,45],[3,5],[7,8],[3,6],[3,10],[7,20],[17,3],[17,45]]
    # Output: 6
    # Expected: 3
    solution3 = Solution()
    print(solution3.maxEnvelopes(
        [[1, 15], [7, 18], [7, 6], [7, 100], [2, 200], [17, 30], [17, 45], [3, 5], [7, 8], [3, 6], [3, 10], [7, 20],
         [17, 3], [17, 45]]))
         

if __name__ == '__main__':
    main()       



1143. Longest Common Subsequence

# dp[i][j]  The meaning is : about  s1[1..i]  and  s2[1..j], Their  LCS  The length is  dp[i][j].
''' NOTE:  about m That's ok n Two dimensional array of columns  java 2D array initialization :int[][] dp = new int[m + 1][n + 1]; <= Before and after  python 2D array initialization :dp = [[0 for col in range(n+1)] for row in range(m+1)] <= Go before you go  '''
class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        m = len(text1)
        n = len(text2)
        #  Definition :text1[0..i-1] and text2[0..j-1] Of lcs The length is dp[i][j]
        dp = [[0 for col in range(n+1)] for row in range(m+1)]
        #  The goal is :text1[0..m-1] and text2[0..n-1] Of lcs length , namely dp[m][n]
        # base case: dp[0][..]=dp[..][0]=0

        for i in range(1, m + 1, 1):
            for j in range(1, n + 1, 1):
                #  Now? i and j from 1 Start , Therefore, it is necessary to reduce 1
                if text1[i - 1] == text2[j - 1]:
                    # text1[i-1] and text2[j-1] equal , Then the character must be in lcs in 
                    dp[i][j] = dp[i - 1][j - 1] + 1
                else:
                    # text1[i-1] and text2[j-1] It's not equal , Then one of these two characters must be absent lcs in 
                    dp[i][j] = max(dp[i][j - 1], dp[i - 1][j])

        return dp[m][n]


def main():
    # Input: text1 = "abcde", text2 = "ace"
    # Output: 3
    # Explanation: The longest common subsequence is "ace" and its length is 3.
    solution1 = Solution()
    print(solution1.longestCommonSubsequence(text1="abcde", text2="ace"))

    # Input: text1 = "abc", text2 = "abc"
    # Output: 3
    # Explanation: The longest common subsequence is "abc" and its length is 3.
    solution2 = Solution()
    print(solution2.longestCommonSubsequence(text1="abc", text2="abc"))

    # Input: text1 = "abc", text2 = "def"
    # Output: 0
    # Explanation: There is no such common subsequence, so the result is 0.
    solution3 = Solution()
    print(solution3.longestCommonSubsequence(text1="abc", text2="def"))


if __name__ == '__main__':
    main()




1425. Constrained Subsequence Sum






原网站

版权声明
本文为[Nonxinyou]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206131120416451.html