Skip to content

Instantly share code, notes, and snippets.

@thmain
Created May 27, 2018 06:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/68c0d0013f9e7ec0f7bdff801631f276 to your computer and use it in GitHub Desktop.
Save thmain/68c0d0013f9e7ec0f7bdff801631f276 to your computer and use it in GitHub Desktop.
public class SubSetSumRecursion {
public static void find(int[] A, int currSum, int index, int sum,
int[] solution) {
if (currSum == sum) {
System.out.println("\nSum found");
for (int i = 0; i < solution.length; i++) {
if (solution[i] == 1) {
System.out.print(" " + A[i]);
}
}
} else if (index == A.length) {
return;
} else {
solution[index] = 1;// select the element
currSum += A[index];
find(A, currSum, index + 1, sum, solution);
currSum -= A[index];
solution[index] = 0;// do not select the element
find(A, currSum, index + 1, sum, solution);
}
return;
}
public static void main(String[] args) {
int[] A = { 3, 2, 7, 1};
int[] solution = new int[A.length];
find(A, 0, 0, 6, solution);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment