组合

来源:互联网 发布:网易顶级域名是什么 编辑:程序博客网 时间:2024/04/29 23:00
组给出两个整数n和k,返回从1......n中选出的k个数的组合。
样例
例如 n = 4 且 k = 2
返回的解为:

[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]

import java.util.ArrayList;import java.util.List;import java.util.Scanner;/** * 组给出两个整数n和k,返回从1......n中选出的k个数的组合。样例例如 n = 4 且 k = 2返回的解为:[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]] *  * @author Dell * */public class Test152 {   public static List<List<Integer>> combine(int n,int k)   {    int[] a=new int[n];    for(int i=0;i<n;i++)    {           a[i]=i+1;    }   List<Integer> list=new ArrayList<>();   List<List<Integer>> result=new ArrayList<>();   backtracking(a,k,0,list,result);   return result;   }   public static void backtracking(int[]a, int k, int start, List<Integer> list, List<List<Integer>> result)   {   if(k==0)   result.add(new ArrayList<>(list));   else   {   for(int i=start;i<a.length;i++)   {   list.add(a[i]);   backtracking(a,k-1,i+1,list,result);   list.remove(list.size()-1);   }      }      }public static void main(String[] args) {    Scanner sc=new Scanner(System.in);    int n=sc.nextInt();    int k=sc.nextInt();    List<List<Integer>> list=combine(n,k);        System.out.println(list);}}


原创粉丝点击