LeetCode(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],
]
代码:

lass Solution {
public:
    
    vector<vector<int> > ans;
    vector<vector<int> > combine(int n, int k) {
        vector<int> tmp;
        DFS(1, n, k, tmp);
        return ans;
    }
    
    void DFS(int begin, int n, int k, vector<int>& tmp)
    {
        if(begin > n && k != 0)//如果begin超过n但是k有没有到0则返回
            return ;
        if(k == 0)//如果k到了0则已经都选完了
        {
            ans.push_back(tmp);
            return ;
        }
        tmp.push_back(begin);
        DFS(begin + 1, n, k - 1, tmp);//选择 begin
        tmp.pop_back();
        DFS(begin + 1, n, k, tmp);//不选择begin
    }
};


你可能感兴趣的:(面试,DFS,组合数)