Dynamic Programming -Dynamic Programming (DP)

Dynamic Programming

Dynamic programming approach experience

Dynamic programming is a general interview questions written in high-frequency algorithm, master necessary. Dynamic programming is a central idea in solving the current problem, the results may have been obtained by a combination of current and previous restrictions introduced delivery results. Before this, the calculations have been preserved, so greatly reduces the time complexity.

The key to solving the problem of dynamic programming is to find out the state of expression, that is, how to derive from the previous results in the results. In addition, there are some difficult issues many restrictions increase the problem, pumping silk cocoon stripping need, to solve the problem. After finding expression in the state, it is divided into three steps to solve the problem:

I. Definition of memory used to save the results of each step, and in accordance with the title initialization, some simple subject only related to the previous step you need to define memory.

II. Expression according to the state transition of each step is sequentially calculated result, various restrictions should be noted here.

III. The data in the memory according to the requirements as a result of a problem returned.

Dynamic Programming topic summary

The longest substring palindromic

Description Title: Given a string s, to find sthe longest substring palindromic. You may assume that sthe maximum length of 1000.

Problem-solving ideas: Dynamic Programming most important thing is to find the state transition matrix, whether this question Layer 2 cycle is traversed palindrome string, first define a whole to False two-dimensional array, the result depends on ending the current iteration of equality and removing the string ending whether two palindromic string conditions, whereby the state transition matrix can be obtained as: \ (DP [L, R & lt] = (S [L] == S [R & lt] and (R & lt - L <2 or DP = [. 1 + L, R & lt -. 1])) \) .

Code

class Solution:
    def longestPalindrome(self, s: str) -> str:
        size = len(s)
        if size <= 1:
            return s
        # 二维 dp 问题
        # 状态:dp[l,r]: s[l:r] 包括 l,r ,表示的字符串是不是回文串
        # 定义二维列表,并规定全部取值为False,这也是后面为什么没有输出False的原因
        dp = [[False for _ in range(size)] for _ in range(size)]

        longest_l = 1
        res = s[0]

        # 因为只有 1 个字符的情况在最开始做了判断
        # 左边界一定要比右边界小,因此右边界从 1 开始
        for r in range(1, size):
            for l in range(r):
                # 状态转移方程:如果头尾字符相等并且中间也是回文
                # 在头尾字符相等的前提下,如果收缩以后不构成区间(最多只有 1 个元素),直接返回 True 即可
                # 否则要继续看收缩以后的区间的回文性
                # 重点理解 or 的短路性质在这里的作用
                if s[l] == s[r] and (r - l <= 2 or dp[l + 1][r - 1]):
                    dp[l][r] = True
                    cur_len = r - l + 1
                    if cur_len > longest_l:
                        longest_l = cur_len
                        res = s[l:r + 1]
        return res

10. The regular expression match

32. The maximum validity brackets

44. wildcard matching

53. The maximum and subsequence

Description Title: Given an array of integers nums, and find a maximum of the successive sub-array (sub-array comprising a least one element), and has returned to its maximum.

Outline of Solution: Thinking a: First, the first number and the maximum continuous array initialization; and then through the array, and sequentially adding; When the maximum value exceeds the previous replaces, when it is less than 0 reinitialized to zero. Thinking two: dynamic programming. Through the array, the state transition matrix is: dp [i] = dp [ i-1] + dp [i], but the idea of such a same surface of the continuous current is greater than 0 and continues plus the current value is less than 0 when recalculated. Since only this question is no single definition of a list of previous results off to store the results.

A thought:

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        max_val, cur = nums[0], 0
        for x in nums:
            cur += x
            if cur > max_val:
                max_val = cur
            if cur < 0:
                cur = 0
        return max_val

Thinking two:

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        n = len(nums)
        max_sum = nums[0]
        for i in range(1, n):
            if nums[i - 1] > 0:
                nums[i] += nums[i - 1] 
            max_sum = max(nums[i], max_sum)

        return max_sum

62. The different paths

Description Title: a robot mxn grid in a top left corner (FIG below the starting point labeled "Start"). The robot can only move one step to the right or down. Robot trying to reach the bottom right corner of the grid (in the following figure labeled "Finish"). Q. How many different paths there are in total?

Problem-solving ideas: Typical dynamic programming problem, first creates a list for the result, and then successively calculated from the known cycle a first row and first column, the state transition matrix is: dp [i, j] = dp [i-1 , j] + dp [i, j-1], the final output d [-1, -1].

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        # 动态规划
        # 定义二维空列表
        dp = [[0 for i in range (n+1)] for i in range(m+1)]
        # 初始化第一行列表的值
        for i in range(1, n+1):
            dp[1][i] = 1
        # 由状态转移矩阵求解列表其余的值  
        for i in range(2, m+1):
            for j in range(1, n+1):
                dp[i][j] = dp[i-1][j] + dp[i][j-1]
        # 返回最后的值       
        return dp[m][n]

63. The different paths II

Description Title: a robot mxn grid in a top left corner (FIG below the starting point labeled "Start"). The robot can only move one step to the right or down. Robot trying to reach the bottom right corner of the grid (in the following figure labeled "Finish").

Problem-solving ideas: the idea of solving the same problem, except that when faced with an obstacle, not a list of values derived from the state transition matrix calculations, but directly to zero.

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        # 同样是动态规划,不过在障碍处标记为0,并且不进行遍历;
        m, n = len(obstacleGrid), len(obstacleGrid[0])
        dp = [[0 for i in range(n+1)] for j in range(m+1)]
        for i in range(1, n+1):
            if obstacleGrid[0][i-1] == 1:
                break
            else:
                dp[1][i] = 1
        
        for i in range(2,m+1):
            for j in range(1,n+1):
                if obstacleGrid[i-1][j-1]:
                    dp[i][j] = 0
                else:
                    dp[i][j]=dp[i-1][j]+dp[i][j-1]
        return dp[m][n]

64. minimum path and

Description Title: Given a non-negative integer m X n- grid, find a path from left to bottom right, so that the sum of the minimum number of paths. Note: you can only move one step down or to the right

Outline of Solution: A typical dynamic programming problem, old routines, defined two-dimensional list, initializing the first row and first column value, traversing the list transfer matrix dp [i, j] = min (dp [i according to the state, J- 1], dp [i-1 , j]) + grid [i, j]

class Solution(object):
    def minPathSum(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        m , n = len(grid) , len(grid[0])
        dp = [[0x7fffffff for x in range(n+1)] for x in range(m+1)]
        dp[0][1] = dp[1][0] = 0             
        for i in range(1,m+1):
            for j in range(1,n+1):
                dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i-1][j-1]
        return dp[m][n]

70. stairs

Topic Description: Suppose you are climbing stairs. Need n order to reach your roof. Every time you can climb one or two steps. How many different ways can climb to the roof of it?

Outline of Solution: typical dynamic programming, the state transition matrix: dp [i] = dp [ i-1] + dp [i-2]. This is the same Fibonacci number.

class Solution:
    def climbStairs(self, n: int) -> int:
        if n == 1:
            return 1
        elif n == 2:
            return 2
        else:
            a, b =1, 2
            for i in range(n-2):
                c = a + b
                a = b
                b = c
            return c

91. The decoding method

Description Title: one containing the letters A-Zof the message is coded in the following manner:

'A' -> 1
'B' -> 2
...
'Z' -> 26

Given a number containing only non-null string, a decoding method of calculating the total number.

Problem-solving ideas: This is similar questions and problems climbing stairs, not the same as a lot more restrictions. If (1) the last two digits can be decoded, i.e. is between 1 to 26; (2) only when the last one decoding, the last digit is 0;

class Solution:
    def numDecodings(self, s: str) -> int:
        if not s: return 0
        n = len(s)
        dp = [0] * n
        dp[0] = 1 if s[0] != '0' else 0
        for i in range(1, n):
            if 10 <= int(s[i - 1:i + 1]) <= 26:
                dp[i] += dp[i - 2] if i >= 2 else 1
            if s[i] != '0':
                dp[i] += dp[i - 1]
        return dp[n - 1]

And a minimum path 120. The triangular

Description Title: Given a triangle to find a top-down and a minimum path. Each step can move to the next line adjacent nodes.

For example, given triangle:

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

Top-down and minimum path 11 (i.e., 2 + 3 + 5 + 1 = 11).

Problem-solving ideas:

Note: If you can only use the extra space O (n) of (n is the number of rows in the triangle) to solve this problem, then your algorithm will be a plus.

class Solution:
    def minimumTotal(self, triangle: List[List[int]]) -> int:
        mini, M = triangle[-1], len(triangle)
        for i in range(M - 2, -1, -1):
            for j in range(len(triangle[i])):
                mini[j] = triangle[i][j] + min(mini[j], mini[j+1])    
        return mini[0]

Guess you like

Origin www.cnblogs.com/ffjsls/p/12121510.html