Skip to content

Commit 3721cef

Browse files
committed
0416. Partition Equal Subset Sum V1.0
1 parent ff2f528 commit 3721cef

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import java.util.Arrays;
2+
3+
/**
4+
* @author changleamazing
5+
* @date 2020/10/11 18:25
6+
**/
7+
public class Solution {
8+
public boolean canPartition(int[] nums) {
9+
if(nums.length == 0){
10+
return false;
11+
}
12+
int sum = Arrays.stream(nums).sum();
13+
return sum % 2 == 0 && canPartition(nums,sum / 2);
14+
15+
}
16+
17+
public boolean canPartition(int[] nums,int sum){
18+
boolean[][] dp = new boolean[nums.length][sum + 1];
19+
if(nums[0] <= sum){
20+
dp[0][nums[0]] = true;
21+
}
22+
for (int i = 1; i < dp.length; i++) {
23+
if(nums[i] == sum){
24+
dp[i][sum] = true;
25+
return true;
26+
}
27+
for(int j = 0;j < dp[0].length;j++){
28+
dp[i][j] = dp[i - 1][j];
29+
30+
if(nums[i] <= j){
31+
dp[i][j] |= dp[i - 1][j - nums[i]];
32+
}
33+
}
34+
}
35+
return dp[nums.length - 1][sum];
36+
}
37+
38+
public static void main(String[] args) {
39+
int[] a = {1, 2, 3, 4};
40+
Solution solution = new Solution();
41+
solution.canPartition(a);
42+
}
43+
44+
}
45+
46+
47+
48+
49+
50+
51+

0 commit comments

Comments
 (0)