問題:數組
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.element
Note:get
Example 1:it
Input: [1, 5, 11, 5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:io
Input: [1, 2, 3, 5] Output: false Explanation: The array cannot be partitioned into equal sum subsets.
解決:class
① 多重揹包,使用動態規劃解決。dp[i][j]表示前i個數,和爲j。遍歷
1). 判斷數組中全部數的和是否爲偶數,由於奇數是不可能有解的;集合
2). dp[i][j] = Math.max(dp[i - 1][j],dp[i - 1][j - nums[i - 1]] + nums[i - 1])動態規劃
3).若是最後dp[nums.length][sum / 2] = sum / 2,則返回true.co
class Solution { //60ms
public boolean canPartition(int[] nums) {
if(nums.length == 0) return false;
int sum = 0;
for(int n : nums){//求全部數的和
sum += n;
}
if(sum % 2 == 1) return false;//不存在兩個和相等的子集
sum = sum / 2;
int[][] dp = new int[nums.length + 1][sum + 1];
for(int i = 0;i <= nums.length;i ++){
for(int j = 0;j <= sum;j ++){
if(i == 0) {//表示前0個數,因此價值均爲0;
dp[i][j] = 0;
}else if(j < nums[i - 1]){//在裝第i-1個數時,先判斷剩餘容量j是否大於nums[i-1]
dp[i][j] = dp[i - 1][j]; //小於表示空間不夠,因此維持不變
}else{//空間夠,就經過比較大小來判斷是否該放入第i-1個數
dp[i][j]=Math.max(dp[i - 1][j],dp[i - 1][j - nums[i - 1]] + nums[i - 1]);
}
}
}
return dp[nums.length][sum] == sum;
}
}
② 定義dp[i]表示數字i是不是原數組的任意個子集合之和,初始化dp[0]爲true,咱們須要遍歷原數組中的數字,對於遍歷到的每一個數字nums[i],咱們須要更新咱們的dp數組,要更新[nums[i], sum]之間的值,那麼對於這個區間中的任意一個數字j,若是dp[j - nums[i]]爲true的話,那麼dp[j]就必定爲true。遞推公式以下:dp[j] = dp[j] || dp[j - nums[i]] (nums[i] <= j <= target)
class Solution { //33ms public boolean canPartition(int[] nums) { if(nums.length == 0) return false; int sum = 0; for(int n : nums){//求全部數的和 sum += n; } if(sum % 2 == 1) return false;//不存在兩個和相等的子集 sum = sum / 2; boolean[] dp = new boolean[sum + 1]; dp[0] = true; for (int i = 0;i < nums.length;i ++){ for (int j = sum;j >= nums[i];j --){ dp[j] = dp[j] || dp[j - nums[i]]; } } return dp[dp.length - 1]; } }