concept
【】 Geekforgeeks
Dynamic Programming is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of subproblems, so that we do not have to re-compute them when needed later. This simple optimization reduces time complexities from exponential to polynomial. For example, if we write simple recursive solution for Fibonacci Numbers, we get exponential time complexity and if we optimize it by storing solutions of subproblems, time complexity reduces to linear.
Dynamic programming is a simple recursive for a major optimization methods. When we see the recursive solution called repeatedly for the same input, we can optimize the dynamic programming method is repeated. The method is the result of simple storage sub-problems, so we do not need to repeat the calculation at the time of their subsequent use. This simple optimization will reduce the time complexity from exponential to polynomial. For example, if we write about simple recursive solution fibonacci series, we get the complexity of the time index, but if we optimize storage by sub-problems, to reduce the time complexity linear.
Scenarios
General disintegration ideas
Dynamic programming four elements:
1. Status
2. The state transition equation
3. Initialize
4. Results
Topic exercise
Fibonacci sequence leetcode 509
The largest contiguous subsequence leetcode 53
// Input: [-2,1, -3,4, -1,2,1, -5,4], // Output: 6 @ Explanation: continuous subarray [4, -1,2,1] and the largest for 6. class Solution { public int maxSubArray ( int [] the nums) { int n-= nums.length, maxSum the nums = [0 ]; for ( int I =. 1; I <n-; ++ I) { IF (the nums [I -. 1 ]> 0) the nums [I] + = the nums [I -. 1 ]; maxSum = Math.max (the nums [I], maxSum); } return maxSum; } }
Wildcard matching leetcode 44
// Input: // S = "adceb" // P = "A * B *" // Output: to true // explained: the first '*' can match the empty string, the second '*' matches string "DCE." class Solution { public Boolean IsMatch (S string, string P) { int m = s.length (), = n- p.length (); Boolean [] [] = F new new Boolean [m +. 1 ] [n-+. 1 ]; F [ 0] [0] = to true ; for ( int I =. 1; I <= n-; I ++ ) { F [ 0] [I] = F [0] [I -. 1] && p.charAt (I -. 1) == '*' ; *' } for(int i = 1; i <= m; i++){ for(int j = 1; j <= n; j++){ if(s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '?'){ f[i][j] = f[i - 1][j - 1]; } if(p.charAt(j - 1) == '*'){ f[i][j] = f[i][j - 1] || f[i - 1][j]; } } } return f[m][n]; } }
Reference material
1. https://www.geeksforgeeks.org/dynamic-programming/
2. https://leetcode-cn.com/problems/wildcard-matching/solution/dong-tai-gui-hua-si-yao-su-by-a380922457-4/
3. https://leetcode-cn.com/problems/maximum-subarray/solution/zui-da-zi-xu-he-by-leetcode/