-
Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathSubsetSum.java
36 lines (31 loc) · 1.17 KB
/
SubsetSum.java
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
package com.thealgorithms.dynamicprogramming;
public final class SubsetSum {
private SubsetSum() {
}
/**
* Test if a set of integers contains a subsetRecursion that sums to a given integer.
*
* @param arr the array containing integers.
* @param sum the target sum of the subsetRecursion.
* @return {@code true} if a subsetRecursion exists that sums to the given value, otherwise {@code false}.
*/
public static boolean subsetSum(int[] arr, int sum) {
int n = arr.length;
boolean[][] isSum = new boolean[n + 1][sum + 1];
// Initialize the first column to true since a sum of 0 can always be achieved with an empty subsetRecursion.
for (int i = 0; i <= n; i++) {
isSum[i][0] = true;
}
// Fill the subsetRecursion sum matrix
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= sum; j++) {
if (arr[i - 1] <= j) {
isSum[i][j] = isSum[i - 1][j] || isSum[i - 1][j - arr[i - 1]];
} else {
isSum[i][j] = isSum[i - 1][j];
}
}
}
return isSum[n][sum];
}
}