程式碼隨想錄訓練營第五十三天 | 動態規劃
阿新 • • 發佈:2022-12-05
今天是程式碼隨想錄的第五十三天,今天依舊是子集問題
class Solution { public int longestCommonSubsequence(String text1, String text2) { int n = text1.length(); int m = text2.length(); int[][] dp = new int[n+1][m+1]; for(int i = 1 ; i<= n; i++){ chartemp1 = text1.charAt(i-1); for(int j = 1; j<=m; j++){ char temp2 = text2.charAt(j-1); if(temp1 == temp2){ dp[i][j] = dp[i-1][j-1]+1; } else{ dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]); } } }return dp[n][m]; } }
dp[i][j]是dp[i][j]前一位的最大公共元素,每找到一位相同的,那麼就可以加上1.
class Solution { public int maxUncrossedLines(int[] nums1, int[] nums2) { int n = nums1.length; int m = nums2.length; int[][] dp = new int[n+1][m+1]; for(int i = 1; i<=n; i++){for(int j = 1; j<=m; j++){ if(nums1[i-1] == nums2[j-1]){ dp[i][j] = dp[i-1][j-1]+1; } else{ dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]); } } } return dp[n][m]; } }
轉化成最長子序列問題後,和上一題一樣的思路
class Solution { public int maxSubArray(int[] nums) { int n = nums.length; int[] dp = new int[n]; dp[0] = nums[0]; for(int i = 1; i < n; i++){ if(nums[i-1]>0){ nums[i] += nums[i-1]; } dp[i] = Math.max(dp[i-1], nums[i]); } return dp[n-1]; } }
好像又迴歸到普通的dp了
刷題計劃已經臨近尾聲!加油!!