leetcode解题: Partition Equal Subset Sum (416)

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.

解法1:DP: O(N*M), M是要找的子数组的和的大小。

这题参考了这个的解法, 这一类的dp的题目里,dp[i]的数组的下标往往表示的是能取得值。
这里呢,首先想到要能分成两个同等大小的数组,原数组的和一定必须是偶数,而且这样的话每一个子数组的和是sum/2
有了这个之后,dp[i]的定义就变成了原数组是否有一个子数组他的和是i。
进一步,我们可以遍历整个数组,对于每一个数x,我们从target开始往下update, dp[x] = dp[x] || dp[target - x]
就是说,如果dp[x]要存在的话,dp[target - x]一定也存在。

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
bool canPartition(vector<int>& nums) {
if (nums.size() <= 1) {
return false;
}
int sum = accumulate(nums.begin(), nums.end(), 0);
if (sum % 2 != 0) {
return false;
}
int target = sum / 2;
vector<bool> dp(target + 1, false);
dp[0] = true;
for (int i = 0; i < nums.size(); ++i) {
for (int j = target; j >= nums[i]; --j) {
dp[j] = dp[j] || dp[j - nums[i]];
}
}
return dp[target];
}
};

Java

1