【Leetcode】77. 组合

题目

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

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

题解

这道题目我就不做解析了,就是全排列的变种,全排列用backtrack的方法,我们之前已经解析过好几期了,都是一套解题模板,直接记住这种backtrack题目的模板即可快速A掉。

java版本

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        backtrack(res, n, 1, k, new ArrayList<>());
        return res;
    }

    public void backtrack(List<List<Integer>> res, int n, int num, int k, List<Integer> list) {
        if (list.size() == k) {
            res.add(new ArrayList<>(list));
        } else {
            for (int i = num; i <= n; i++) {
                list.add(i);
                backtrack(res, n, i + 1, k, list);
                list.remove(list.size() - 1);
            }
        }
    }
}

python版本

class Solution:
    def backtrack(self, res, n, nums, k, current):
        if len(current) == k:
            res.append(current.copy())
        else:
            for i in range(nums, n + 1):
                current.append(i)
                self.backtrack(res, n, i + 1, k, current)
                current.pop()

    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        res = []
        self.backtrack(res, n, 1, k, [])
        return res

回溯题目

《【Leetcode】77. 组合》

    原文作者:Acceml
    原文地址: https://segmentfault.com/a/1190000016503581
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞