LeetCode 77. Combinations

LeetCode 77. Combinations (组合)

题目

链接

https://leetcode.cn/problems/combinations/

问题描述

你可以按 任何顺序 返回答案。

示例

输入:n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

提示

1 <= n <= 20
1 <= k <= n

思路

回溯法,首先从第一个点开始,一直到满足条件,同时要考虑到剪枝。

复杂度分析

时间复杂度 O(n2)
空间复杂度 O(k)

代码

Java

    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();

    public List<List<Integer>> combine(int n, int k) {
        combineHelper(n, k, 1);
        return result;
    }
  
    public void combineHelper(int n, int k, int startIndex){
        if (path.size() == k){
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i <= n - (k - path.size()) + 1; i++){
            path.add(i);
            combineHelper(n, k, i + 1);
            path.removeLast();
        }
    }
posted @ 2022-06-13 16:44  cheng102e  阅读(16)  评论(0编辑  收藏  举报