-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathParitionSum.java
More file actions
51 lines (40 loc) · 1.56 KB
/
ParitionSum.java
File metadata and controls
51 lines (40 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.Arrays;
public class ParitionSum {
public static void main(String[] args) {
int[] nums = {10,2,8,2,2};
System.out.println(canPartition(nums));
}
public static boolean canPartition(int[] num) {
int n = num.length;
// find the total sum
int sum = 0;
for (int i = 0; i < n; i++)
sum += num[i];
// if 'sum' is a an odd number, we can't have two subsets with same total
if(sum % 2 != 0)
return false;
// we are trying to find a subset of given numbers that has a total sum of ‘sum/2’.
sum /= 2;
boolean[][] dp = new boolean[n][sum + 1];
// populate the sum=0 columns, as we can always for '0' sum with an empty set
for(int i=0; i < n; i++)
dp[i][0] = true;
// with only one number, we can form a subset only when the required sum is equal to its value
for(int s=1; s <= sum ; s++) {
dp[0][s] = (num[0] == s ? true : false);
}
// process all subsets for all sums
for(int i=1; i < n; i++) {
for(int s=1; s <= sum; s++) {
// if we can get the sum 's' without the number at index 'i'
if(dp[i-1][s]) {
dp[i][s] = dp[i-1][s];
} else if (s >= num[i]) { // else if we can find a subset to get the remaining sum
dp[i][s] = dp[i-1][s-num[i]];
}
}
}
// the bottom-right corner will have our answer.
return dp[n-1][sum];
}
}