🟡 剑指 Offer II 080. 含有 k 个元素的组合
LeetCode 提示
题目难度 中等
原题链接 🔗 leetcode
题解1#
dfs,从左到右,每个位置考虑要或者不要当前的数字,加到tmp里,tmp满员则加入res
class Solution {    private List<Integer> tmp = new ArrayList<>();    private List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> combine(int n, int k) {        dfs(1, n, k);        return res;    }
    private void dfs(int cur, int n, int k) {        if (tmp.size() + (n-cur+1) < k) {            return;        }
        if (tmp.size() == k) {            res.add(new ArrayList<>(tmp));            return;        }
        tmp.add(cur);        dfs(cur+1, n, k);        tmp.remove(tmp.size()-1);        dfs(cur+1, n, k);    }}