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.
这道题让分成两个部分,那么就是找一些数字加起来==sum/2
就是说对于num[i]可以加也可以不加(0或1)
模型成把一个容量为(sum/2)的背包装满,背包问题,就像geeks for geeks写的,这个backtracking 过程中存在大量重复操作O(2^n)
DP子问题:n个物品(n层),goal容量0-v
“将前i件物品放入容量为v的背包中”
dp[i][v] = dp[i-1][v] || dp[i-1][v-nums[i]];
public boolean canPartition(int[] nums) {
int sum = 0;
for(int i = 0; i < nums.length; i++)
sum += nums[i];
if(sum%2 == 1) return false;
int n = sum/2;
boolean[] dp = new boolean[n+1];
dp[0] = true;
for(int i = 0; i <nums.length; i++){
for(int j = n; j >= nums[i]; j--){
dp[j] = dp[j] || dp[j-nums[i]];
}
}
System.out.println(Arrays.toString(dp));
return dp[n];
}
没有评论:
发表评论