-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpartition_equal_subset_sum.go
75 lines (65 loc) · 1.21 KB
/
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
package leetcode
// iterative dp solution
// TC: O(n * m) where n is length of nums and m is sum(nums)//2
// SC: O(m)
func canPartition(nums []int) bool {
s := sum(nums)
if s%2 != 0 {
return false
}
half := s / 2
dp := make([]bool, half+1)
dp[half] = true
for _, num := range nums {
for el, state := range dp {
if state == false {
continue
}
new_el := el - num
if new_el == 0 {
return true
}
if new_el > 0 {
dp[new_el] = true
}
}
}
return false
}
// recursive memoized solution
// TC: O(n * m) where n is length of nums and m is sum(nums)//2
// SC: O(n * m)
func canPartition2(nums []int) bool {
s := sum(nums)
if s%2 != 0 {
return false
}
half := s / 2
return dfs(0, half, make(map[State]bool), nums)
}
func dfs(idx, curr int, cache map[State]bool, nums []int) bool {
if curr == 0 {
return true
}
if idx >= len(nums) {
return false
}
state := State{idx, curr}
if val, ok := cache[state]; ok == true {
return val
}
res := dfs(idx+1, curr-nums[idx], cache, nums) || dfs(idx+1, curr, cache, nums)
cache[state] = res
return res
}
func sum(nums []int) int {
res := 0
for _, el := range nums {
res += el
}
return res
}
type State struct {
idx int
curr int
}