publicclassMain{publicstaticvoidmain(String[] args){int[] nums =newint[]{1,3,2,5};int sum=0;for(int num : nums) sum += num;// 和为奇数时,不可能划分成两个和相等的集合if(sum %2!=0){System.out.println(false);return;}int n = nums.length;
sum = sum /2;boolean[][] dp =newboolean[n +1][sum +1];//初始化,背包没有空间的时候就相当于装满了for(int i =0; i <= n; i++)
dp[i][0]=true;for(int i =1; i <= n; i++){for(int j =1; j <= sum; j++){if(j - nums[i -1]<0){// 背包容量不足,不能装入第 i 个物品
dp[i][j]= dp[i -1][j];}else{// 装入或不装入背包
dp[i][j]= dp[i -1][j]|| dp[i -1][j - nums[i -1]];}}}System.out.println(dp[n][sum]);}}
代码优化,二维dp数组变一维
publicclassMain{publicstaticvoidmain(String[] args){int[] nums =newint[]{1,3,7,5};int sum =0;for(int num : nums) sum += num;// 和为奇数时,不可能划分成两个和相等的集合if(sum %2!=0){System.out.println(false);return;}int n = nums.length;
sum = sum /2;boolean[] dp =newboolean[sum +1];// base case
dp[0]=true;for(int i =0; i < n; i++){for(int j = sum; j >=0; j--){if(j - nums[i]>=0){
dp[j]= dp[j]|| dp[j - nums[i]];}}}System.out.println(dp[sum]);}}