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++
Java