[leetCode刷题笔记]77. Combinations

来源:互联网 发布:石油进口数据 编辑:程序博客网 时间:2024/06/06 20:27

使用backtrack的方法。对过程进行递归。

public class Solution {    public List<List<Integer>> combine(int n, int k) {        List<List<Integer>> combs = new ArrayList<List<Integer>>();        combine(combs, new ArrayList<Integer>(), 1, n, k);        return combs;    }    private void combine(List<List<Integer>> combs, List<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);            // before enter next step, delete old step            comb.remove(comb.size() - 1);        }    }}


0 0