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],
]
这道题让求1到n共n个数字里k个数的组合数的所有情况
public class l77_Combinations {
ArrayList<ArrayList<Integer>> res=new ArrayList<>();
ArrayList<Integer> temp=new ArrayList<>();
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
dfs(n,k,1);
return res;
}
void dfs(int n,int k,int start){
if(temp.size()==k)
//重新创建一个Arraylist对象存储
res.add(new ArrayList<Integer>(temp));
for(int i=start;i<=n;i++){
temp.add(i);
dfs(n,k,i+1);
temp.remove(temp.size()-1);
}
}
public static void main(String[] args) {
l77_Combinations s=new l77_Combinations();
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
int k=scanner.nextInt();
ArrayList<ArrayList<Integer>> ans=s.combine(n,k);
System.out.println(ans);
}
}