Leetcode-77_ Combinations(组合)-深搜解法-【C++】

77. Combinations

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

For example,

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

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

题目大意:

其实就是要求C(n,k),n取k有多少种组合。

解题思路:

使用dfs解即可

class Solution {
public:
    vector > res;
    void generateCombined(int n,int k,int start,vector c){
        if(c.size()==k){
            res.push_back(c);
            return;
        }
        for(int i=start;i > combine(int n, int k) {
        if(n<=0||k<=0||k>n)
            return res;
        vector c;
        generateCombined(n,k,1,c);
    }
};

结果:78ms

Leetcode-77_ Combinations(组合)-深搜解法-【C++】_第1张图片

你可能感兴趣的:(【Leetcode题解】,算法学习及Leetcode题解)