416.分割等和子串
给你一个 只包含正整数 的 非空 数组 nums 。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
示例 1:
输入:nums = [1,5,11,5]
输出:true
解释:数组可以分割成 [1, 5, 5] 和 [11] 。
示例 2:
输入:nums = [1,2,3,5]
输出:false
解释:数组不能分割成两个元素和相等的子集。
提示:
1 <= nums.length <= 2001 <= nums[i] <= 100
该题是01背包问题,只需要设立一个数组dp[ i ][ j ]其中 i 表示当前遍历的数组中的数,j 则表示当前背包所剩大小,在本题中则为当前容量。
代码可优化为一维数组。
java
public static void main(String[] args) { // 测试用
int[] sums = {1,5,11,5};
System.out.println(canPartition(sums));
}
public static boolean canPartition(int[] nums) {
if (nums.length == 0){
return false;
}
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
}
if (sum % 2 == 1){
return false;
}
int target = sum / 2;
boolean[][] res = new boolean[nums.length][target + 1];
if (nums[0] <= target){
res[0][nums[0]] = true;
}
for (int i = 1; i < res.length; i++) {
for (int j = 0; j < res[0].length; j++) {
res[i][j] = res[i - 1][j];
if (nums[i] == j){
res[i][j] = true;
continue;
}
if (nums[i] < j){
res[i][j] = (res[i - 1][j] || res[i - 1][j - nums[i]]);
}
}
}
return res[nums.length - 1][target];
}
以上为记录分享用,代码较差请见谅