[leetcode_77]Combinations

简单搜索题,但是题目交代不是很清楚,也可能是自己的英文不大好,就是说给n, 全集为1, 2, 3…n。从里面选k个组成子集,列举所有子集。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
    void combineStep(int n, int step, int k, vector<int>& item, vector<vector<int>>& ans, int count)
    {
        if(step > n+1)
            return;
        if(count == k)
        {
            ans.push_back(item);
            return ;
        }
        else
        {
            item.push_back(step);
            combineStep(n, step+1, k, item, ans, count+1);
            item.pop_back();
            combineStep(n, step+1, k, item, ans, count);
        }
    }
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> ans;
        ans.clear();
        vector<int> item;
        item.clear();
        combineStep(n, 1, k, item, ans, 0);
        return ans;
    }
};
Licensed under CC BY-NC-SA 4.0