LeetCode 77. 组合

题目描述

🔥 77. 组合

思路分析

思路描述

参考代码

1
write your code here

🍏 点击查看 Java 题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        backtrack(res, new ArrayList<>(), n, k, 1);
        return res;
    }

    private void backtrack(List<List<Integer>> result, List<Integer> tempList, int n, int k, int start) {
        if (tempList.size() == k) {
            result.add(new ArrayList<>(tempList)); // 找到一个组合,加入结果集
            return;
        }

        for (int i = start; i <= n; i++) {
            tempList.add(i); // 添加当前元素到临时组合中
            backtrack(result, tempList, n, k, i + 1); // 递归
            tempList.remove(tempList.size() - 1); // 回溯,移除最后一个元素
        }
    }
}

相似题目

题目 难度 题解
组合总和 Medium  
全排列 Medium  
本文作者:
本文链接: https://hgnulb.github.io/blog/67920981
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!