- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSubsetSum.java
More file actions
Latest commit
56 lines (48 loc) · 1.78 KB
/
Copy pathSubsetSum.java
File metadata and controls
56 lines (48 loc) · 1.78 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
52
53
54
55
56
packageDynamicProgramming;
/**
* @author kalpak
*
* Given a set of positive numbers, determine if there exists a subset whose sum is equal to a given number ‘S’.
*
* Example 1: #
*
* Input: {1, 2, 3, 7}, S=6
* Output: True
* The given set has a subset whose sum is '6': {1, 2, 3}
*
*/
publicclassSubsetSum {
publicstaticbooleancanPartition(int[] nums, inttarget) {
boolean[][] dp = newboolean[nums.length][target + 1];
// Now the first column of the memoization table will be to true since we can achieve a target of 0 with empty set
for(inti = 0; i < nums.length; 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 (ints = 1; s <= target; s++) {
dp[0][s] = (nums[0] == s ? true : false);
}
// process all subsets for all sums
for (inti = 1; i < nums.length; i++) {
for (ints = 1; s <= target; 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];
} elseif (nums[i] < s) {
// else include the number and see if we can find a subset to get the remaining
// sum
dp[i][s] = dp[i - 1][s - nums[i]];
}
}
}
returndp[nums.length - 1][target];
}
publicstaticvoidmain(String[] args) {
int[] num = { 1, 2, 3, 7 };
System.out.println(canPartition(num, 6));
num = newint[] { 1, 2, 7, 1, 5 };
System.out.println(canPartition(num, 10));
num = newint[] { 1, 3, 4, 8 };
System.out.println(canPartition(num, 6));
}
}