← Home

416. Partition Equal Subset Sum

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
416

Let's make this one less mysterious. For 416. Partition Equal Subset Sum, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: dynamic programming, bit manipulation.

The notes already sitting in the source point us in the right direction:

  • 0/1 Knapsack Problem
  • https://leetcode.com/problems/partition-equal-subset-sum/discuss/90592/01-knapsack-detailed-explanation
  • time: O(NW), space: O(NW)

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are canPartition.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(NW), space: O(NW)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//0/1 Knapsack Problem
02//https://leetcode.com/problems/partition-equal-subset-sum/discuss/90592/01-knapsack-detailed-explanation
03//Runtime: 1032 ms, faster than 5.04% of C++ online submissions for Partition Equal Subset Sum.
04//Memory Usage: 11 MB, less than 47.06% of C++ online submissions for Partition Equal Subset Sum.
05//time: O(NW), space: O(NW)
06class Solution {
07public:
08    bool canPartition(vector<int>& nums) {
09        int n = nums.size(); //number of objects
10        int capacity = accumulate(nums.begin(), nums.end(), 0);
11        if((capacity & 1) == 1) return false;
12        capacity /= 2;
13        
14        /*
15        the +1 is not padding, it's meaningful!
16        i: number of objects in the backpack
17        j: current weight of backpack
18        dp[i][j]: whether the state: (i, j) exists or not
19        our goal is to find out dp[n][capacity]
20        */
21        vector<vector<bool>> dp(n+1, vector<bool>(capacity+1, false));
22
23        for(int i = 0; i <= n; i++){
24            for(int j = 0; j <= capacity; j++){
25                if(i == 0 && j == 0){
26                    //choose nothing, make up weight = 0
27                    dp[i][j] = true;
28                    continue;
29                }else if(j == 0){
30                    //make up weight = 0
31                    dp[i][j] = true;
32                    continue;
33                }else if(i == 0){
34                    //no object to choose, but need to make up weight j > 0
35                    dp[i][j] = false;
36                    continue;
37                }
38                /*
39                not choose this object,
40                so the weight remains the same(= j)
41                */
42                dp[i][j] = dp[i-1][j];
43                /*
44                need to check whether the remaining capacity 
45                still allows us to choose object i:
46                j >= nums[i] means we still have enough capacity
47                
48                note that dp[i] corresponds to nums[i-1]!!
49                (because the i in dp[i] means number of items!)
50                */
51                if(j - nums[i-1] >= 0){
52                    dp[i][j] = dp[i][j] | dp[i-1][j-nums[i-1]];
53                }
54            }
55        }
56
57        return dp[n][capacity];
58    }
59};
60
61//optimization, O(N) space
62class Solution {
63public:
64    bool canPartition(vector<int>& nums) {
65        int n = nums.size(); //number of objects
66        int capacity = accumulate(nums.begin(), nums.end(), 0);
67        if((capacity & 1) == 1) return false;
68        capacity /= 2;
69        
70        /*
71        the +1 is not padding, it's meaningful!
72        i: number of objects in the backpack
73        j: current weight of backpack
74        dp[i][j]: whether the state: (i, j) exists or not
75        our goal is to find out dp[n][capacity]
76        */
77        vector<bool> dp(capacity+1, false);
78
79        dp[0] = true;
80        
81        for(int i = 1; i <= n; i++){
82            for(int j = capacity; j >= 0; j--){
83                if(j == 0){
84                    dp[j] = false;
85                }
86                
87                if(j - nums[i-1] >= 0){
88                    dp[j] = dp[j] | dp[j-nums[i-1]];
89                }
90            }
91        }
92
93        return dp[capacity];
94    }
95};
96
97//bitset
98//https://leetcode.com/problems/partition-equal-subset-sum/discuss/90590/Simple-C%2B%2B-4-line-solution-using-a-bitset
99//Runtime: 12 ms, faster than 90.14% of C++ online submissions for Partition Equal Subset Sum.
100//Memory Usage: 9.1 MB, less than 52.94% of C++ online submissions for Partition Equal Subset Sum.
101class Solution {
102public:
103    bool canPartition(vector<int>& nums) {
104        /*
105        Note:
106        Each of the array element will not exceed 100.
107        The array size will not exceed 200.
108        
109        we want to check if we can make up sum/2 by some elements,
110        so we don't care anything > sum/2,
111        and by the Note above,
112        we can inspect that the max possible sum/2 is 100*200/2 = 10000,
113        since we still need place for sum equal to 0(the least significant bit),
114        so totally we need 10001 bits
115        
116        we initialize bits as 1,
117        this is saying that we can choose 0 elements to make up 0(x)
118        this is just for convenience, so that we can use bits |= bits << n;
119        */
120        bitset<10001> bits(1);
121        int sum = accumulate(nums.begin(), nums.end(), 0);
122        /*
123        initially, we can make up 0
124        1st iter: "bits" is set in 0th and nums[0]th bit
125        2nd iter: "bits" is set in 0, nums[0], nums[1] and nums[0]+nums[1]th bit
126        ...
127        */
128        for (auto n : nums) bits |= bits << n;
129        /*
130        need to check if the sum is even first!
131        bits[sum >> 1]: whether we can make up sum/2 by nums's subset
132        */
133        return !(sum & 1) && bits[sum >> 1];
134    }
135};

Cost

Complexity

Time
O(NW), space: O(NW)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.