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],
]
给出数字n和k,找出从1到n中选k个数的组合
思路:
按DFS解,遍历所有的数,用stack保存当前遍历到的数
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (k == 0) {
return result;
}
Stack<Integer> tmp = new Stack<>();
dfs(result, tmp, 1, n, k);
return result;
}
public void dfs(List<List<Integer>> result, Stack<Integer> stack,
int start, int n, int k) {
if (stack.size() == k) {
result.add(new ArrayList<Integer>(stack));
return;
}
for (int i = start; i <= n; i++) {
stack.push(i);
dfs(result, stack, i+1, n, k);
stack.pop();
}
}