Skip to content

Instantly share code, notes, and snippets.

@sdpatil
Created August 8, 2017 14:28
Show Gist options
  • Save sdpatil/fd5ee68a5a4681d54977b3e23aa294c0 to your computer and use it in GitHub Desktop.
Save sdpatil/fd5ee68a5a4681d54977b3e23aa294c0 to your computer and use it in GitHub Desktop.
Generate all subsets of size k
import java.util.ArrayList;
import java.util.List;
/*
Problem: Generate all subsets of size k
Ex. given n = 5 and k =2 generate [1, 2] [1, 3] [1, 4] [1, 5] [2, 3] [2, 4] [2, 5] [3, 4] [3, 5] [4, 5]
Solution: This is backtracking problem in which you pass start index + 1 to next iteration of backtrack
*/
public class GenerateAllSubsetsOfSizeK {
public List<List<Integer>> combination(int n, int k) {
List<List<Integer>> result = new ArrayList<>();
backtrack(n, k, 1, result, new ArrayList<>());
return result;
}
public void backtrack(int n, int k, int startIndex, List<List<Integer>> result,
List<Integer> partialList) {
if (k == partialList.size()) {
result.add(new ArrayList<>(partialList));
return;
}
for (int i = startIndex; i <= n; i++) {
partialList.add(i);
backtrack(n, k, i + 1, result, partialList);
partialList.remove(partialList.size() - 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment