Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
简单的递归题目,入门级别
public class Solution {
static List<List<Integer>> ans = new ArrayList<List<Integer>>();
static ArrayList<Integer> sta = new ArrayList<>();
static boolean[] num = null;
static int k;
// static int used = 0;
public List<List<Integer>> combine(int n, int k) {
ans.clear();
sta.clear();
num = new boolean[n + 1];
this.k = k;
dfs(1);
return ans;
}
public void dfs(int cur){
if(sta.size() == k){
ArrayList<Integer> t = new ArrayList<>();
for(int i : sta){
t.add(i);
}
ans.add(t);
}else if(cur < num.length){
dfs(cur + 1);
if(num[cur] == false){
sta.add(cur);
num[cur] = true;
dfs(cur + 1);
num[cur] = false;
sta.remove(sta.size() - 1);
}
}
}
}