您的位置:首页 > 其它

Leetcode 416. Partition Equal Subset Sum

2017-02-09 16:37 344 查看
子集和问题   

更常见的亦可扩展为背包问题:

0-1 背包问题:

dp[0] = true;
dp[0] = 1;
for(int n: nums){
for(int h=S;h>=n;h--){
dp[h] = dp[h]||dp[h-n];
//dp[h] = dp[h]+dp[h-n]; // roll array.
}
}

更加普遍的背包问题(忘了术语是啥):
dp[0] = true;
dp[0] = 1;
for(int n: nums){
for(int h=0;h>=n,h<=S;h++){
dp[h] = dp[h]||dp[h-n];
//dp[h] = dp[h]+dp[h-n]; // roll array.
}
}

题目链接: Leetcode 416. Partition Equal Subset Sum

典型动态规划问题,下面是采用dp[]数组表示有多少种子集和计数方案

public class Solution {
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;
}
return subsumSet(nums,sum/2);
//return ((sum%2)==1)?false:subsumSet(nums,sum/2);
}

private boolean subsumSet(int[] nums, int S) {
// TODO Auto-generated method stub
// out
//boolean[] dp = new boolean[S+1];
int[] dp = new int[S+1];
//dp[0] = true;
dp[0] = 1;
for(int n: nums){
for(int h=S;h>=n;h--){
//dp[h] = dp[h]||dp[h-n];
dp[h] = dp[h]+dp[h-n];  // roll array.
}
}

//return dp[S]; `

if(dp[S]>=1)
return true;
else{
return false;
}

/*
if(i==0){
if(nums[i]==S) return true;
else return false;
}
// dynamic programming
return subsumSet(nums,S,i-1)||subsumSet(nums,S-nums[i],i-1);
*/
}
}


但是出现如下错误:



将 dp[] 数组改为boolean类型时:有无子集和出现时,代码为下:

public class Solution {
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;
}
return subsumSet(nums,sum/2);
//return ((sum%2)==1)?false:subsumSet(nums,sum/2);
}

private boolean subsumSet(int[] nums, int S) {
// TODO Auto-generated method stub
// out
//boolean[] dp = new boolean[S+1];
//int[] dp = new int[S+1];
dp[0] = true;
//dp[0] = 1;
for(int n: nums){
for(int h=S;h>=n;h--){
dp[h] = dp[h]||dp[h-n];
//dp[h] = dp[h]+dp[h-n];  // roll array.
}
}

return dp[S]; `

/*
if(dp[S]>=1)
return true;
else{
return false;
}
*/

/*
if(i==0){
if(nums[i]==S) return true;
else return false;
}
// dynamic programming
return subsumSet(nums,S,i-1)||subsumSet(nums,S-nums[i],i-1);
*/
}
}


Accepted!

I donot know why?

原因在于整型值溢出了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: