LeetCode 416. Partition Equal Subset Sum
原题链接在这里:https://leetcode.com/problems/partition-equal-subset-sum/description/
题目:
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.
题解:
其实是找有没有sub array的数字和是sum/2. Thus for the other half, sum must be sum/2.
Let dp[j] denotes if there is subarray sum equal to j.
dp[0] = true.
Then for each num in nums, dp[num] would be true.
Thus for j, check if dp[j-num], if dp[j-num] is true. Then dp[j] msut be true.
Time Complexity: O(sum*nums.length). sum = sum(nums)/2.
Space: O(sum).
AC Java:
1 class Solution { 2 public boolean canPartition(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return false; 5 } 6 7 int sum = 0; 8 for(int num : nums){ 9 sum += num; 10 } 11 12 if(sum % 2 == 1){ 13 return false; 14 } 15 16 int target = sum / 2; 17 boolean [] dp = new boolean[target + 1]; 18 dp[0] = true; 19 for(int num : nums){ 20 for(int i = target; i >= num; i--){ 21 dp[i] |= dp[i - num]; 22 } 23 } 24 25 return dp[target]; 26 } 27 }
类似Target Sum 的Method 2.