|
| 1 | +/* |
| 2 | +Problem: LeetCode 416 - Partition Equal Subset Sum |
| 3 | +
|
| 4 | +Key Idea: |
| 5 | +The key idea is to use dynamic programming to determine if it's possible to partition the input array into two subsets with equal sums. |
| 6 | +
|
| 7 | +Approach: |
| 8 | +1. Calculate the sum of all elements in the input array `nums` and store it in a variable `total_sum`. |
| 9 | +2. If the total sum is odd, it's impossible to partition the array into two subsets with equal sums. Return `false` in this case. |
| 10 | +3. Otherwise, initialize a boolean vector `dp` of size `total_sum / 2 + 1`, where `dp[i]` represents whether it's possible to form a subset with a sum of `i`. |
| 11 | + - Initialize `dp[0]` to `true` because an empty subset has a sum of 0. |
| 12 | +4. Iterate through the elements of the input array `nums`: |
| 13 | + - For each element `num`, iterate through the `dp` vector in reverse order from `total_sum / 2` down to `num`. |
| 14 | + - Update `dp[i]` to `true` if either `dp[i]` is already `true` or `dp[i - num]` is `true`. This means we can form a subset with a sum of `i` by either not including the current `num` or including it. |
| 15 | +5. After the iteration, if `dp[total_sum / 2]` is `true`, it's possible to partition the array into two subsets with equal sums; otherwise, it's not possible. |
| 16 | +6. Return `dp[total_sum / 2]` as the result. |
| 17 | +
|
| 18 | +Time Complexity: |
| 19 | +O(n * sum), where `n` is the number of elements in the input array `nums`, and `sum` is the sum of all elements in the array. We fill in the `dp` table with a nested loop. |
| 20 | +
|
| 21 | +Space Complexity: |
| 22 | +O(sum / 2), as we use a boolean vector of size `total_sum / 2 + 1` to store the dynamic programming values. |
| 23 | +*/ |
| 24 | + |
| 25 | +impl Solution { |
| 26 | + pub fn can_partition(nums: Vec<i32>) -> bool { |
| 27 | + let total_sum: i32 = nums.iter().sum(); |
| 28 | + |
| 29 | + if total_sum % 2 != 0 { |
| 30 | + return false; |
| 31 | + } |
| 32 | + |
| 33 | + let target_sum = (total_sum / 2) as usize; |
| 34 | + let mut dp = vec![false; target_sum + 1]; |
| 35 | + dp[0] = true; |
| 36 | + |
| 37 | + for &num in nums.iter() { |
| 38 | + for i in (num as usize..=target_sum).rev() { |
| 39 | + dp[i] = dp[i] || dp[i - num as usize]; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + dp[target_sum] |
| 44 | + } |
| 45 | +} |
0 commit comments