416. Partition Equal Subset Sum

Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

 

Example 1:

Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: nums = [1,2,3,5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.

 

Constraints:

  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= 100

Rust Solution

struct Solution;

impl Solution {
    fn can_partition(nums: Vec<i32>) -> bool {
        let sum: i32 = nums.iter().sum();
        if sum % 2 == 1 {
            return false;
        }
        let half = (sum / 2) as usize;
        let mut dp: Vec<bool> = vec![false; half as usize + 1];
        dp[0] = true;
        let mut max = 0;
        for x in nums {
            let j = x as usize;
            for i in (j..=half.min(max + j)).rev() {
                if dp[i - j] {
                    dp[i] = true;
                    max = max.max(i);
                }
            }
            if dp[half] {
                return true;
            }
        }
        false
    }
}

#[test]
fn test() {
    let nums = vec![1, 5, 11, 5];
    let res = true;
    assert_eq!(Solution::can_partition(nums), res);
    let nums = vec![1, 2, 5];
    let res = false;
    assert_eq!(Solution::can_partition(nums), res);
}

Having problems with this solution? Click here to submit an issue on github.