Given a non-empty array containing only positive integers,find if the array can be
partitioned to two subsets such that the sum of elements in both subsets is equal.
Note:
1.Each of the array element will not exceed 100.
2.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.
题目大意:
给定一个只包含正整数的非空数组,是否可以将这个数组分割成两个子集,使得两个子集的元素之和相等.
解题思路:
方法1:
dfs+剪枝优化
要满足sum(P)=sum(Q),根据sum(P)+sum(Q)=sum(nums),可得sum(P)=sum(nums)/2.此问题转换为
在数组中找出是否存在子集满足target=sum(nums)/2.
只要找到一个temp值等于target即可返回,剪枝的条件是在枚举数组中temp!=target,此外路径之和不能大于target.
可惜超时。
方法2:
动态规划
Go语言实现
package main
import (
"fmt"
"math"
)
func canPartition(nums []int)bool{
flag:=false
sum,temp:=0,0
for _,num:=range nums{
sum+=num
}
if sum%2!=0{//sum为奇数,直接返回false
return false
}
dfs(nums,sum/2,0,0,&temp)
if(temp==sum/2){
flag=true
}
return flag
}
func dfs(nums []int,sum int,index int,ans int,temp *int){
if index>=len(nums){
return
}
if ans==sum{
*temp=sum
return
}
for i:=index;i<len(nums)&&(*temp)!=sum;i++{//剪枝(*temp)!=sum、ans+nums[i]>sum
if ans+nums[i]>sum{
continue
}
ans+=nums[i]
fmt.Println(ans," ",sum)
dfs(nums,sum,i+1,ans,temp)
ans-=nums[i]
}
}
func canPartitionOne(nums []int)bool{
sum:=0
maxNum:=math.MinInt64
for _,num:=range nums{
sum+=num
maxNum=Max(maxNum,num)
}
target:=sum>>1
if sum%2!=0||target<maxNum{//sum为奇数,直接返回false
return false
}
if target==maxNum{
return true
}
dp:=make([]int,target+1)
dp[0]=1//初始化key为0时,value为1个
for _,i:=range nums{
for j:=target;j>=i;j--{
dp[j]+=dp[j-i]
}
if dp[target]!=0{//表示已经找到一组子集满足条件
return true
}
}
return false
}
func Max(a,b int)int{
if a>b{
return a
}
return b
}
func main(){
nums:=[]int{14,9,8,4,3,2,4,6}
//fmt.Println(canPartition(nums))
fmt.Println(canPartitionOne(nums))
}