今天是第四十三天,还是背包问题
class Solution { public int lastStoneWeightII(int[] stones) { int n = stones.length; int sum = 0; for (int i : stones) { sum += i; } int target = sum >> 1; int[] dp = new int[target + 1]; for (int i = 0; i < n; i++) { for (int j = target; j >= stones[i]; j--) { dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]); } } return sum - 2 * dp[target]; } }
怎么啥都能转化成背包
class Solution { int res = 0; void backTracking(int[]nums,int target,int start,int sum){ if(sum==target && start == nums.length){ res++; return; } if(start>=nums.length) return; backTracking(nums,target,start+1,sum+nums[start]); backTracking(nums,target,start+1,sum-nums[start]); } public int findTargetSumWays(int[] nums, int target) { backTracking(nums,target,0,0); return res; } }
动态规划没看会,回溯看会了
class Solution { public int findMaxForm(String[] strs, int m, int n) { int[][] dp = new int[101][101]; for(String s : strs){ int a = 0; int b = 0; char[] temp = s.toCharArray(); for(char c : temp){ if(c == '0') a++; if(c == '1') b++; } for (int i = m; i >= a; i --) { for (int j = n; j >= b; j --) { dp[i][j] = Math.max(dp[i][j], dp[i - a][j - b] + 1); } } } return dp[m][n]; } }
还是背包
今天的三道题都没太弄懂。。。。好头痛,周末好好学一下重头
标签:target,四十三天,nums,int,训练营,随想录,start,sum,dp From: https://www.cnblogs.com/catSoda/p/16921582.html