给定两个整数n和k,返回1…n中所有可能的k个数的组合。
示例:
输入:
4 2输出:
[
[1,2],
[1,3],
[1,4],
[2,1],
[2,3],
[2,4],
[3,1],
[3,2],
[3,4],
[4,1],
[4,2],
[4,3],
]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestDemo {
public static void main(String[] args) throws IOException {
int n,k;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String inputString=br.readLine();
String stringArray[]=inputString.split(" ");
solution.combine(Integer.parseInt(stringArray[0]),Integer.parseInt(stringArray[1]));
}
}
public class solution {
private static int[] flag=new int[12138];
private static int[] arr=new int[12138];
private static int t;
private static int max;
public static void combine(int n, int k){
t=k;
max=n;
System.out.println("[");
dfs(1,0);
System.out.println("]");
}
public static void dfs(int i,int count){
if(count==t) {
int temp=0;
System.out.print(" [");
for(int q=0;q<t;q++){
temp++;
if(temp<t) {
System.out.print(arr[q]+",");
}else
System.out.println(arr[q]+"],");
}
}
else if(i<=max){
for(int m=1;m<=max;m++){
if(flag[m]!=1){
flag[m]=1;
arr[count]=m;
// count++;
dfs(i+1,count+1);
flag[m]=0;
}
}
}
}
}