1. 程式人生 > >[leetcode] 77. 組合

[leetcode] 77. 組合

ret == desc etc tps code pri combine private

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);
        }
    }
}

[leetcode] 77. 組合