PartitionProblem checks whether the given set can be partitioned into two subsets such that the sum of the elements in both subsets is the same.
(nums []int)
| 9 | // PartitionProblem checks whether the given set can be partitioned into two subsets |
| 10 | // such that the sum of the elements in both subsets is the same. |
| 11 | func PartitionProblem(nums []int) bool { |
| 12 | sum := 0 |
| 13 | for _, num := range nums { |
| 14 | sum += num |
| 15 | } |
| 16 | if sum%2 != 0 { |
| 17 | return false |
| 18 | } |
| 19 | |
| 20 | target := sum / 2 |
| 21 | dp := make([]bool, target+1) |
| 22 | dp[0] = true |
| 23 | |
| 24 | for _, num := range nums { |
| 25 | for i := target; i >= num; i-- { |
| 26 | dp[i] = dp[i] || dp[i-num] |
| 27 | } |
| 28 | } |
| 29 | return dp[target] |
| 30 | } |
no outgoing calls