一、题目
二、代码
class Solution
{
public boolean canPartition(int[] nums)
{
int i,j;
int sum = 0;
int length =0;
length = nums.length;
for(i=0;i<length;i++)
{
sum = sum+nums[i];
}
if(sum%2==1) return false;
int half = sum/2;
int[] dp = new int[half+1];
for(i=0;i<length;i++)
{
for(j=half;j>=nums[i];j--)
{
dp[j] = Math.max(dp[j],dp[j-nums[i]]+nums[i]);
}
if(dp[half] == half) return true;
}
return false;
}
}
三、运行结果
四、附录
二刷
class Solution
{
//星星点灯
public boolean canPartition(int[] nums)
{
int i,j;
int length = nums.length;
System.out.println(" length "+length);
int sum = 0;
for(i=0;i<length;i++) sum+=nums[i];
if(sum%2 == 1 ) return false;
int target = sum/2;
System.out.println(" target "+target);
boolean[] res = new boolean[target+1];
res[0] = true;
//for(i=0;i<=target;i++) res[i] = false;
for(i=0;i<length;i++)
{
if(nums[i]>target) continue;
//System.out.println(" 分割 ");
if(res[target]== true ) return true;
for(j=target;j>=nums[i];j--)
{
//System.out.println(" j "+j);
//if((res[j]||res[j-nums[i]])==true) System.out.println(" j "+j+" i "+i);
res[j] = res[j]||res[j-nums[i]];
}
}
//使用滚动数组的01背包问题
return res[target];
}
}