-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path416.Partition-Equal-Subset-Sum.go
84 lines (70 loc) · 1.5 KB
/
416.Partition-Equal-Subset-Sum.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// https://leetcode.com/problems/partition-equal-subset-sum/description/
//
// algorithms
// Medium (38.87%)
// Total Accepted: 61.3k
// Total Submissions: 157.7k
// beats 70.83% of golang submissions
package leetcode
var hashMap map[point]bool
type point struct {
idx int
cntSum int
}
func canPartition(nums []int) bool {
numsSum := 0
for _, n := range nums {
numsSum += n
}
if numsSum%2 == 1 {
return false
}
hashMap = make(map[point]bool)
return resursive(nums, len(nums), 0, 0, numsSum>>1)
}
func resursive(nums []int, length, cntSum, idx, numsSum int) bool {
if cntSum == numsSum {
return true
}
if cntSum > numsSum || idx == length {
return false
}
for i := idx; i < length; i++ {
p := point{
idx: i,
cntSum: cntSum,
}
if _, ok := hashMap[p]; ok {
continue
}
if resursive(nums, length, cntSum+nums[i], i+1, numsSum) {
return true
}
hashMap[point{
idx: i,
cntSum: cntSum,
}] = true
}
return false
}
// 其实递归就能做,最好的做法
func canPartition(nums []int) bool {
sum := 0
for i := 0; i < len(nums); i++ {
sum += nums[i]
}
if sum%2 == 1 {
return false
}
// sum=sum/2
return helperPartition(nums, 0, 0, len(nums)-1, sum)
}
func helperPartition(nums []int, sum1, sum2, pos, total int) bool {
if sum2 > total/2 || sum1 > total/2 {
return false
}
if sum1 == total/2 {
return pos >= -1
}
return helperPartition(nums, sum1+nums[pos], sum2, pos-1, total) || helperPartition(nums, sum1, sum2+nums[pos], pos-1, total)
}