Given a non-empty array 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.
Note:
- Each of the array element will not exceed 100.
- The array size will not exceed 200.
Example 1:
Input: [1, 5, 11, 5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5] Output: false Explanation: The array cannot be partitioned into equal sum subsets.
数组是否可分为两个子集,使得两个子集的元素和相等
看成一个背包大小为 sum/2 的 0-1 背包问题。
C++:
1 class Solution { 2 public: 3 bool canPartition(vector<int>& nums) { 4 int sum = 0 ; 5 for(int num : nums){ 6 sum += num ; 7 } 8 if (sum%2!=0){ 9 return false ; 10 } 11 int W = sum/2 ; 12 vector<bool> dp(W+1,false) ; 13 dp[0] = true ; 14 for(int num : nums){ 15 for(int i = W ; i >= num ; i--){ 16 dp[i] = (dp[i] || dp[i-num]) ; 17 } 18 } 19 return dp[W] ; 20 } 21 };