[Leetcode] Combinations

Combinations 题解

题目来源:https://leetcode.com/problems/combinations/description/


Description

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example

For example,
If n = 4 and k = 2, a solution is:

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

Solution

class Solution {
private:
    void dfs(vector<vector<int>>& res, vector<int>& path, int begin, int n, int k) {
        if (path.size() == k) {
            res.push_back(path);
        } else {
            for (int i = begin; i <= n; i++) {
                path.push_back(i);
                dfs(res, path, i + 1, n, k);
                path.pop_back();
            }
        }
    }
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> res;
        if (k == 0) {
            res.push_back(vector<int>());
            return res;
        }
        vector<int> path;
        dfs(res, path, 1, n, k);
        return res;
    }
};

解题描述

这道题题意是,给出数字nk,求在数字1~n的范围中取k个数字的所有情况,也就是求组合。上面用到的解法是递归DFS的方法。不过由于被选择的数字在n确定的情况下是确定的,所以可以使用非DFS的办法来解决。比如评论区给出的一个迭代枚举的办法就非常巧妙:

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> res;
        vector<int> temp(k, 0);
        int i = 0;
        while (i >= 0) {
            temp[i]++;
            if (temp[i] > n) {
                i--;
            } else if (i == k - 1) {
                res.push_back(temp);
            } else {
                i++;
                temp[i] = temp[i - 1];
            }
        }
        return res;
    }
};

原文地址:https://www.cnblogs.com/yanhewu/p/8422751.html