背包问题
对于面试的话,其实掌握01背包,和完全背包,就够用了,最多可以再来一个多重背包。
416. Partition Equal Subset Sum
Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.
题目解析:
- dp[i] 表示容量为i的背包最多能放多少
- 对于数组中的每一个元素,遍历从target到nums[i],找到dp[i]的最大值
代码:
class Solution {
public boolean canPartition(int[] nums) {
int sum = Arrays.stream(nums).sum();
if (sum % 2 != 0) return false;
int target = sum / 2;
int[] dp = new int[target + 1];
dp[0] = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = target; j >= nums[i]; j--) {
dp[j] = Math.max(dp[j], dp[j - nums[i]] + nums[i]);
}
if (dp[i] == target) return true;
}
return dp[target] == target;
}
}