试题
Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Note:
Each of the array element will not exceed 100.
The array size will not exceed 200.
Example 1:
Input: [1, 5, 11, 5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.
代码
看成0-1背包问题:能否用当前的数组组合出值为W的子集。
class Solution {
public boolean canPartition(int[] nums) {
int sum = 0;
for(int num:nums){
sum += num;
}
if(sum%2==1) return false;
int W = sum/2;
boolean[] dp = new boolean[W+1];
dp[0] = true; // 初始值考虑的是dp[i-num]情况,当i==num时应该为true。
for(int num:nums){
for(int i=W; i>=num; i--){
dp[i] = dp[i] || dp[i-num]; //如果不加num时dp[i]已经为true,那么说明从开始到num这么多数是可以组合出和为dp[i]的,反之,加入num,就看dp[i-num]加上num能否组合出。
}
}
return dp[W];
}
}