對於這個問題,我們可以先對集合求和,得出 sum,把問題轉化爲揹包問題:
給一個可裝載重量爲 sum / 2 的揹包和 N 個物品,每個物品的重量爲 nums[i]。現在讓你裝物品,是否存在一種裝法,能夠恰好將揹包裝滿?
Input: [1, 5, 11, 5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
public boolean canPartition(int[] nums) {
int sum = 0;
for(int num : nums) {
sum += num;
}
//若sum爲奇數,則一定爲false
if(sum % 2 != 0) return false;
//揹包容量爲sum/2
sum = sum / 2;
//dp[i]表示:和爲i是否可以分割
boolean[] dp = new boolean[sum + 1];
dp[0] = true;
for(int i = 1; i < nums.length; i ++) {
for(int j = sum; j >= nums[i]; j --) {
dp[j] = dp[j] || dp[j - nums[i]];
}
}
return dp[sum];
}