--- back combination

combination

77. Combinations (Medium)

If n = 4 and k = 2, a solution is:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

Subject description:

  To the two numbers n and k shown, the output of all combinations composed of number k, in the range of the number of 1-n, and the form of the above embodiment;

Analysis of ideas:

  Permutation problem, backtracking solutions

Code:

public List<List<Integer>>combine(int n,int k){
    List<List<Integer>>res=new ArrayList<>();
    if(n<k)
        return res;
    List<Integer>list=new ArrayList<>();
    backtracking(res,list,1,n,k);
    return res;
}
public void backtracking(List<List<Integer>>res,List<Integer>list,int start,int n,int k){
    if(k==0){
        res.add(new ArrayList<>(list));
        return;
    }
    for(int i=start;i<=n-k+1;i++){//进行剪枝,满足序列中的元素递增
        list.add(i);
        backtracking(res,list,i+1,n,k-1);
        list.remove(list.size()-1);
    }
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11113338.html