Skip to content

Commit aae1a63

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 416_Partition_Equal_Subset_Sum.java
1 parent 61aa21f commit aae1a63

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public boolean canPartition(int[] nums) {
3+
if (nums == null || nums.length == 0) {
4+
return false;
5+
}
6+
7+
int totalSum = 0;
8+
for (int num : nums) {
9+
totalSum += num;
10+
}
11+
if (totalSum % 2 == 1) {
12+
return false;
13+
}
14+
totalSum /= 2;
15+
16+
boolean[][] dp = new boolean[nums.length + 1][totalSum + 1];
17+
dp[0][0] = true;
18+
19+
for (int i = 1; i <= nums.length; i++) {
20+
for (int j = 1; j <= totalSum; j++) {
21+
if (nums[i - 1] <= j) {
22+
dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i - 1]];
23+
} else {
24+
dp[i][j] = dp[i - 1][j];
25+
}
26+
}
27+
}
28+
29+
return dp[nums.length][totalSum];
30+
}
31+
}

0 commit comments

Comments
 (0)