LeetCode题解:Combinations

来源:互联网 发布:艾默生网络能源 编辑:程序博客网 时间:2024/05/16 12:36

Combinations

Given two integers n and k, return all possible combinations ofk 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],]

思路:

递归填数即可。

题解:

class Solution {public:    int max;    int unused;    vector<vector<int>> ret;    vector<int> used;        void try_combine(int i)    {        if (unused == 0)        {            ret.push_back(used);            return;        }                if (i > max)            return;                    try_combine(i + 1);                used.push_back(i);        --unused;                try_combine(i + 1);                used.pop_back();        ++unused;    }        vector<vector<int> > combine(int n, int k) {        ret.clear();        used.clear();        max = n;        unused = k;                try_combine(1);        return ret;    }};


原创粉丝点击