【每日一题-leetcode】 77.组合

77.组合

  1. 组合

难度中等256

给定两个整数 n 和 k,返回 1 … n *中所有可能的 *k 个数的组合。

示例:

输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

回溯法

回溯法是一种选优搜索法,按选优条件向前搜索,已达到目标,但当搜索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回在走的技术为回溯法。

public static List<List<Integer>> combine(int n,int k){
        List<List<Integer>> combs = new ArrayList<>();
        combine(combs,new ArrayList<Integer>(),1,n,k);
        return combs;
    }

    private static void combine(List<List<Integer>> combs, ArrayList<Integer> comb, int start, int n, int k) {
        if(k == 0){
            combs.add(new ArrayList<Integer>(comb));
            return;
        }
        for (int i = start; i <= n; i++) {
            comb.add(i);
            combine(combs,comb,i+1,n,k-1);
            comb.remove(comb.size()-1); //执行到这一步 说明 在combs里添加过一次  比如 1,2  需要删除 2   [1]去和下一次配对
            //它的作用就是每成功添加一对的话 删除最后一个。再次配对  [1,2] [1,3] [1,4]  [2,3] [2,4] [3,4]
        }
    }
原文地址:https://www.cnblogs.com/qxlxi/p/12860620.html