|
| 1 | +# 416. Partition Equal Subset Sum |
| 2 | + |
| 3 | +## Intuition |
| 4 | + |
| 5 | +The problem can be transformed into finding if we can select some numbers from the array that sum up to half of the total sum. This is essentially a 0/1 knapsack problem where we need to determine if we can fill a knapsack of capacity sum/2 using the given numbers. |
| 6 | + |
| 7 | +## Approach |
| 8 | + |
| 9 | +1. First, calculate the total sum of the array |
| 10 | +2. If the sum is odd, return false as equal partition is impossible |
| 11 | +3. Divide the sum by 2 to get our target sum |
| 12 | +4. Use dynamic programming to solve: |
| 13 | + - Create a dp array where dp[j] represents if we can make sum j using the numbers |
| 14 | + - For each number, we can either include it or not include it |
| 15 | + - Use a temporary array to avoid affecting previous calculations |
| 16 | + - If at any point we can make the target sum, return true |
| 17 | +5. As an optimization, we also: |
| 18 | + - Sort the array first |
| 19 | + - Use binary search to check if target sum exists directly in array |
| 20 | + |
| 21 | +## Complexity |
| 22 | + |
| 23 | +- Time complexity: O(n * sum) |
| 24 | +- Space complexity: O(sum) |
| 25 | + |
| 26 | +## Keywords |
| 27 | + |
| 28 | +- Dynamic Programming |
| 29 | +- 0/1 Knapsack |
| 30 | +- Binary Search |
| 31 | + |
| 32 | +## Code |
| 33 | + |
| 34 | +```go |
| 35 | +func canPartition(nums []int) bool { |
| 36 | + sum := 0 |
| 37 | + for _, num := range nums { |
| 38 | + sum += num |
| 39 | + } |
| 40 | + if sum & 1 == 1 { |
| 41 | + return false |
| 42 | + } |
| 43 | + sum >>= 1 |
| 44 | + sort.Ints(nums) |
| 45 | + _, flag := slices.BinarySearch(nums, sum) |
| 46 | + if flag { |
| 47 | + return true |
| 48 | + } |
| 49 | + dp := make([]bool, sum + 1) |
| 50 | + dp[0] = true |
| 51 | + for _, num := range nums { |
| 52 | + tmp := make([]bool, sum + 1) |
| 53 | + tmp[0] = true |
| 54 | + for j := 1; j <= sum ; j += 1 { |
| 55 | + tmp[j] = dp[j] |
| 56 | + if j >= num { |
| 57 | + tmp[j] = (tmp[j] || dp[j - num]) |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + if tmp[sum] { |
| 62 | + return true |
| 63 | + } |
| 64 | + |
| 65 | + copy(dp, tmp) |
| 66 | + } |
| 67 | + return dp[sum] |
| 68 | +} |
| 69 | +``` |
0 commit comments