Combinations

LeetCode Q 77 - Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

Solution : Backtracking

Code:

private List<List<Integer>> res;
public List<List<Integer>> combine(int n, int k) {
	res = new ArrayList<>();
	if (n == 0 || k.length == 0) return res;
	Arrays.sort(cand);
	backtrack(n, k, 1, new ArrayList<>());
	return res;
}

private void backtrack (int n, int k, int pos, List<Integer> temp) {
	if (temp.size() == k) {
		res.add(new ArrayList(temp)); return;
	}
	if (temp.size() > k) return;

	for (int i = pos; i <= n; i++) {
		if (!temp.contains(i)) {
			temp.add(i);
			backtrack(n, k, i + 1, temp);
			temp.remove(temp.size() - 1);
		}
	}
}

   Reprint policy


《Combinations》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC