DFS_77. 组合

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

示例:

输入: n = 4, k = 2
输出:

[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combinations


思路:

基本和排列的一样

第一步:特殊情况判断,如果k == 0,直接返回

第二步:基本变量的定义,需要一个变量判断是否已经遍历过(组合可以不用),需要一个变量记录当前位置已经添加上了哪些变量

第三步:dfs函数定义,确定返回条件,当层次和k相等就返回记录下现在的path

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        //特殊情况判断
        List<List<Integer>> res = new LinkedList();
        if (k == 0){
            return res;
        }
        Deque<Integer> path = new ArrayDeque<Integer>();
        dfs(n,k,0,path,res);
        return res;
    }

    private void dfs(int n,int k, int depth, Deque<Integer> path, List<List<Integer>> res) {
        if (depth == k){
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < n; i++) {
            path.addFirst(i + 1);
            dfs(i,k,depth + 1,path,res);
            path.removeFirst();
        }
    }
}
原文地址:https://www.cnblogs.com/zzxisgod/p/13372378.html