-
Notifications
You must be signed in to change notification settings - Fork 72
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
17 additions
and
29 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
40 changes: 14 additions & 26 deletions
40
src/main/java/g0401_0500/s0416_partition_equal_subset_sum/Solution.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,39 +1,27 @@ | ||
package g0401_0500.s0416_partition_equal_subset_sum; | ||
|
||
// #Medium #Top_100_Liked_Questions #Array #Dynamic_Programming #Level_2_Day_13_Dynamic_Programming | ||
// #2022_07_16_Time_2_ms_(99.96%)_Space_42.3_MB_(90.38%) | ||
// #2022_12_29_Time_27_ms_(94.53%)_Space_41.8_MB_(95.29%) | ||
|
||
public class Solution { | ||
public boolean canPartition(int[] nums) { | ||
int sum = 0; | ||
int sums = 0; | ||
for (int num : nums) { | ||
sum = sum + num; | ||
sums += num; | ||
} | ||
if (sum % 2 != 0) { | ||
// odd | ||
if ((sums % 2) == 1) { | ||
return false; | ||
} | ||
sum = sum / 2; | ||
// if use primitive boolean array will make default value to false | ||
// we need the default value "null" to help us to do the memo | ||
Boolean[] dp = new Boolean[sum + 1]; | ||
return sumTo(nums, sum, 0, dp); | ||
} | ||
|
||
private boolean sumTo(int[] nums, int sum, int index, Boolean[] dp) { | ||
if (sum == 0) { | ||
return true; | ||
} | ||
if (sum < 0) { | ||
return false; | ||
} | ||
if (index == nums.length) { | ||
return false; | ||
} | ||
if (dp[sum] != null) { | ||
return dp[sum]; | ||
sums /= 2; | ||
int n = nums.length; | ||
boolean[] dp = new boolean[sums + 1]; | ||
dp[0] = true; | ||
for (int num : nums) { | ||
for (int sum = sums; sum >= num; sum--) { | ||
dp[sum] = dp[sum] || dp[sum - num]; | ||
} | ||
} | ||
// use the number or not use the number | ||
dp[sum] = sumTo(nums, sum - nums[index], index + 1, dp) || sumTo(nums, sum, index + 1, dp); | ||
return dp[sum]; | ||
return dp[sums]; | ||
} | ||
} |