-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsubsetSum.java
38 lines (30 loc) · 1.01 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
37
38
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = Integer.parseInt(br.readLine());
}
int tar = Integer.parseInt(br.readLine());
printTargetSumSubsets(arr, 0, "", 0, tar);
}
// set is the subset
// sos is sum of subset
// tar is target
public static void printTargetSumSubsets(int[] arr, int idx, String set, int sos, int tar) {
if(sos > tar){
return;
}
if(idx == arr.length){
if(sos == tar){
System.out.println(set + ".");
}
return;
}
printTargetSumSubsets(arr, idx + 1, set + arr[idx] + ", ", sos + arr[idx], tar);
printTargetSumSubsets(arr, idx + 1, set, sos, tar);
}
}