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.
Solution:DP
思路: 將數(shù)組分成兩個bi_sum = sum / 2的置侍。
dp[i]: 表示數(shù)字i是否是原數(shù)組的任意個子集合之和,那么我們我們最后只需要返回dp[target]就行了页徐。
我們初始化dp[0]為true愈案,由于題目中限制了所有數(shù)字為正數(shù),那么我們就不用擔(dān)心會出現(xiàn)和為0或者負數(shù)的情況返顺。
遞歸公式: 我們需要遍歷原數(shù)組中的數(shù)字禀苦,對于遍歷到的每個數(shù)字nums[i],我們需要更新我們的dp數(shù)組遂鹊,要更新[nums[i], target]之間的值振乏,那么對于這個區(qū)間中的任意一個數(shù)字j,如果dp[j - nums[i]]為true的話秉扑,那么dp[j]就一定為true慧邮,于是地推公式如下:
dp[j] = dp[j] || dp[j - nums[i]] (nums[i] <= j <= target)
即:外層遍歷對每一個元素a,內(nèi)層遍歷求得用+上這個元素a所有能得到的value情況
題目類似:377. Combination Sum IV
Time Complexity: O(value*N) Space Complexity: O(value)
Solution Code:
public class Solution {
public boolean canPartition(int[] nums) {
// check edge case
if (nums == null || nums.length == 0) {
return true;
}
// preprocess
int volumn = 0;
for (int num : nums) {
volumn += num;
}
if (volumn % 2 != 0) {
return false;
}
volumn /= 2;
// dp def
boolean[] dp = new boolean[volumn + 1];
// dp init
dp[0] = true;
// dp transition
for (int i = 1; i <= nums.length; i++) {
for (int j = volumn; j >= nums[i-1]; j--) {
dp[j] = dp[j] || dp[j - nums[i-1]];
}
}
return dp[volumn];
}
}