LeetCode-动态规划
动态规划不在于记住dp table里填什么,而在于找到subproblems。
53. Maximum Subarray 最大子序列和
https://leetcode.com/problems/maximum-subarray/
题目:给定整数数组nums,查找具有最大和的连续子数组(至少包含一个数字)并返回其和。
思路:在[-2,1,-3,4,-1,2,1,-5,4]对应的dp table中,index=3对应的subproblem是从index=0到index=3这个子列的最大子序列和是多少。对于每个subproblem,有两种选择,一种仅选择当前子列的最后一位,一种是选择之前的最大值加上当前值,选择二者中较大的那个。在dp table中表示就是[-2,1,-2,4,3,5,6,1,5],最大值为6。
class Solution { public int maxSubArray(int[] nums) { int res = Integer.MIN_VALUE; int cur = 0; for(int num : nums){ cur = Math.max(cur+num, num); res = Math.max(res, cur); } return res; } }
72. Edit Distance 最短编辑距离
https://leetcode.com/problems/edit-distance/
题目:给定两个单词Word 1和Word2,找到将word 1转换为Word2所需的最小操作数。允许对一个单词执行以下3种操作:插入字符、删除字符、替换字符。
思路:
class Solution { public int minDistance(String word1, String word2) { int a = word1.length(); int b = word2.length(); int[][] dp = new int[b+1][a+1]; dp[0][0] = 0; for(int i = 1; i < a+1; i++) { dp[0][i] = i; } for(int i = 1; i < b+1; i++) { dp[i][0] = i; } for(int j = 1; j < b+1; j++) { for(int i = 1; i < a+1; i++) { if(word1.charAt(i-1) == word2.charAt(j-1)){ dp[j][i] = dp[j-1][i-1]; } else { int temp = Math.min(dp[j-1][i], dp[j-1][i-1]); dp[j][i] = Math.min(temp, dp[j][i-1]) + 1; } } } return dp[b][a]; } }
120. Triangle 三角形
https://leetcode.com/problems/triangle/
题目:给定一个三角形,从上到下寻找最小路径和。每一步您都可以移动到下面行中的相邻数字。
思路:
class Solution { public int minimumTotal(List<List<Integer>> triangle) { if(triangle == null || triangle.size() == 0) return 0; int m = triangle.size(); int n = triangle.get(m-1).size(); int[] M = new int[n]; // last row -> M for(int i = 0; i < n; i++) { M[i] = triangle.get(m-1).get(i); } for(int i = n-2; i >= 0; i--) { List<Integer> cur = triangle.get(i); for(int j = 0; j < cur.size(); j++) { M[j] = Math.min(M[j], M[j+1]) + cur.get(j); } for(int num : M) { System.out.print(num + " "); } System.out.println(); } return M[0]; } }
152. Maximum Product Subarray 最大乘积子阵
https://leetcode.com/problems/maximum-product-subarray/
题目:给定整数数组num,在具有最大乘积的数组(至少包含一个数字)中查找连续子数组。
思路:
class Solution { public int maxProduct(int[] nums) { int n = nums.length; if(n == 0){ return 0; } int[] maxdp = new int[n]; int[] mindp = new int[n]; maxdp[0] = nums[0]; mindp[0] = nums[0]; int maxProduct = nums[0]; for(int i = 1; i < n; i++){ if(nums[i] > 0){ maxdp[i] = Math.max(maxdp[i - 1] * nums[i], nums[i]); mindp[i] = Math.min(mindp[i - 1] * nums[i], nums[i]); } else{ maxdp[i] = Math.max(mindp[i - 1] * nums[i], nums[i]); mindp[i] = Math.min(maxdp[i - 1] * nums[i], nums[i]); } maxProduct = Math.max(maxProduct, maxdp[i]); } return maxProduct; } }
300. Longest Increasing Subsequence 最长上升子序列
https://leetcode.com/problems/longest-increasing-subsequence/
题目:给定一个未排序的整数数组,找出最长上升子序列的长度。
思路:
class Solution { public int lengthOfLIS(int[] nums) { if(nums.length == 0) return 0; int n = nums.length; int[] dp = new int[n]; dp[0] = 1; int max = 1, curMax = 1; boolean flag = false; for(int i = 1; i < n; i++) { for(int j = i-1; j >= 0; j--) { if(nums[i] > nums[j]) { curMax = Math.max(curMax, dp[j]); flag = true; } } if(flag) { dp[i] = curMax + 1; } else { dp[i] = 1; } curMax = 1; flag = false; max = Math.max(max, dp[i]); } return max; } }
二分法:
class Solution { public int lengthOfLIS(int[] nums) { if (nums.length == 0) { return 0; } int result = 0; /** store tails of each increasing subsequence with different length *eg: 3, 5, 1, 8, 2, 12 * 1 * 1, 2 * 3, 5, 8 * 3, 5, 8, 12 * tails = {1, 2, 8, 12} * */ /** we do not care about what elements are in each subsequence, we only care about tails of them, * because every time we only compare with their tails to decide which subsequence could we add new item * and update the entire structure */ int[] tails = new int[nums.length]; /**(1) if x is larger than all tails, append it, increase the size by 1 * (2) if tails[i-1] < x <= tails[i], update tails[i] */ for (int item : nums) { int left = 0, right = result; /** Use binary search to find the correct tail for new item * * KEY POINTS: find the smallest ceiling of every new number from the existed tails and replace that * ceiling number with new number * * CORNER CASE: if left = right at the first iteration, so do not need to worry about the tails array * does not have any items */ while (left != right) { int mid = (left + right) / 2; if (tails[mid] < item) { left = mid + 1; } else { right = mid; } } //update tails of current subsequence with length of left + 1 tails[left] = item; //if updated subsequence is the longest one, increase result size by 1 if (left == result) { result++; } } return result; } }
322. Coin Change 换硬币
https://leetcode.com/problems/coin-change/
题目:你会得到不同面额的硬币和总金额。编写一个函数来计算弥补这个数量所需的最少硬币数。如果这个数额的钱不能由任何组合的硬币,返回-1。
思路:
class Solution { public int coinChange(int[] coins, int amount) { int n = coins.length; int[] dp = new int[amount+1]; for(int i = 1; i < amount+1; i++) { dp[i] = amount+1; } dp[0] = 0; for (int i = 1; i <= amount; i++) { int temp = i; int cur = 0; for(int j = 0; j < n; j++) { if(coins[j] > temp) continue; cur = 1 + dp[temp-coins[j]]; dp[i] = Math.min(dp[i], cur); } } if(dp[amount] < amount+1) { return dp[amount]; } else { return -1; } } }
416. Partition Equal Subset Sum 分成和相等的两个子集
https://leetcode.com/problems/partition-equal-subset-sum/
题目:给定一个只包含正整数的非空数组,请查找该数组是否可以划分为两个子集,以便两个子集中的元素之和相等。
思路:
class Solution { public boolean canPartition(int[] nums) { int n = nums.length; int total = 0, target = 0; for(int i = 0; i < n; i++) { total += nums[i]; } if(total % 2 == 1) return false; target = total / 2; boolean[] dp = new boolean[target+1]; for(int i = 0; i < target+1; i++) { dp[i] = false; } dp[0] = true; for(int i = 0; i < n; i++) { for(int j = target; j >= nums[i]; j--) { dp[j] = dp[j] | dp[j-nums[i]]; } } return dp[target]; } }
771. Jewels and Stones 宝石和石头
https://leetcode.com/problems/jewels-and-stones/
题目:字符串J代表宝石的类型,字符串S代表你拥有的石头。S中的每一个字符都是你所拥有的一种石头。你想知道你有多少石头属于宝石。J中的字母是独立的,而J和S中的所有字符都是字母。字母区分大小写,因此“a”被认为是一种不同于“A”的石头。
思路:
class Solution { public int numJewelsInStones(String J, String S) { int jl = J.length(); int sl = S.length(); int[][] dp = new int[jl+1][sl+1]; for(int i = 0; i < jl+1; i++) { dp[i][0] = 0; } for(int i = 0; i < sl+1; i++) { dp[0][i] = 0; } for(int i = 1; i < jl+1; i++) { int temp = 0; for(int j = 1; j < sl+1; j++) { if(S.charAt(j-1)==J.charAt(i-1)) temp++; dp[i][j] = temp + dp[i-1][j]; } } return dp[jl][sl]; } }
动态规划:
// http://oj.leetcode.com/problems/triangle/ (最短路径)
http://oj.leetcode.com/problems/subsets/ (另一种形式)
http://oj.leetcode.com/problems/subsets-ii/
// http://oj.leetcode.com/problems/edit-distance/ (经典)
http://oj.leetcode.com/problems/word-break/
http://oj.leetcode.com/problems/word-break-ii/
http://oj.leetcode.com/problems/unique-binary-search-trees/ (动态规划避免递归)
http://oj.leetcode.com/problems/unique-paths-ii/
http://oj.leetcode.com/problems/scramble-string/
http://oj.leetcode.com/problems/palindrome-partitioning/
http://oj.leetcode.com/problems/palindrome-partitioning-ii/
http://oj.leetcode.com/problems/interleaving-string/
http://oj.leetcode.com/problems/distinct-subsequences/
http://oj.leetcode.com/problems/decode-ways/
http://oj.leetcode.com/problems/gray-code/
http://oj.leetcode.com/problems/minimum-path-sum/

浙公网安备 33010602011771号