[leetcode] 77. 组合

77. 组合

递归枚举搜就好

class Solution {

    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> ans = new ArrayList<>();

        List<Integer> cur = new ArrayList<>();

        dfs(n, k, 0, cur, ans);
        return ans;
    }

    private void dfs(int n, int k, int last, List<Integer> cur, List<List<Integer>> ans) {
        if (k == 0) {
            ans.add(new ArrayList<>(cur));
            return;
        }
        for (Integer i = last + 1; i <= n; i++) {
            cur.add(i);
            dfs(n, k - 1, i, cur, ans);
            cur.remove(i);
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/acbingo/p/9390093.html