https://leetcode.cn/problems/partition-equal-subset-sum/
题目要求
给你一个 只包含正整数 的 非空 数组 nums 。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
贪心
class Solution {
boolean flag = false;
public boolean canPartition(int[] nums) {
int n = nums.length;
int total = 0;
for (int i = 0; i < n; i++) {
total += nums[i];
}
if (total % 2 != 0)
return false;
backtrack(0, nums, total / 2);
return flag;
}
public void backtrack(int index, int[] nums, int target) {
if (target < 0)
return;
if (target == 0) {
flag = true;
return;
}
for (int i = index; i < nums.length; i++) {
backtrack(i + 1, nums, target - nums[i]);
}
}
}
- 本题使用贪心会超时
动态规划
class Solution {
public boolean canPartition(int[] nums) {
if (nums == null || nums.length == 0)
return false;
int n = nums.length;
int total = 0;
for (int num : nums) {
total += num;
}
if (total % 2 != 0)
return false;
int target = total / 2;
int[] dp = new int[target + 1];
for (int i = 0; i < n; i++) {
for (int j = target; j >= nums[i]; j--) {
dp[j] = Math.max(dp[j], dp[j - nums[i]] + nums[i]);
}
}
return dp[target] == target;
}
}
- 01背包相对于本题,主要要理解,题目中物品是nums[i],重量是nums[i],价值也是nums[i],背包体积是sum/2。