Skip to content
本页目录

LeetCode 77. 组合

题目描述

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

示例:

javascript
输入: (n = 4), (k = 2);
输出: [
  [2, 4],
  [3, 4],
  [2, 3],
  [1, 2],
  [1, 3],
  [1, 4],
];

来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/combinations 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

直接套用组合题解题模板即可

javascript
var combine = function (n, k) {
  let res = [];
  let dfs = (t, start) => {
    if (t.length === k) {
      res.push(t);
      return;
    }
    for (let i = start; i <= n; i++) {
      t.push(i);
      dfs(t.slice(), i + 1);
      t.pop();
    }
  };
  dfs([], 1);
  return res;
};
cpp
class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> res;
        vector<int> t;
        function<void(int)> dfs = [&](int start) {
            if (t.size() == k) {
                res.push_back(t);
                return;
            }
            for (int i = start; i <= n; i++) {
                t.push_back(i);
                dfs(i + 1);
                t.pop_back();
            }
        };
        dfs(1);
        return res;
    }
};
java
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> t = new ArrayList<>();
    public List<List<Integer>> combine(int n, int k) {
        dfs(n, k, 1);
        return res;
    }
    void dfs(int n, int k, int start) {
        if (t.size() == k) {
            res.add(new ArrayList<>(t));
            return;
        }
        for (int i = start; i <= n; i++) {
            t.add(i);
            dfs(n, k, i + 1);
            t.remove(t.size() - 1);
        }
    }
}
python
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        res = []
        t = []
        def dfs(start):
            if len(t) == k:
                res.append(t[:])
                return
            for i in range(start, n + 1):
                t.append(i)
                dfs(i + 1)
                t.pop()
        dfs(1)
        return res
javascript
学如逆水行舟,不进则退