Combinations

来源:互联网 发布:中日关系走向 知乎 编辑:程序博客网 时间:2024/06/13 07:13

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],]
class Solution {public:    vector<vector<int> > res;     void execute(int& n,int cur, int count, vector<int>& pre)    {         if (count-- == 0)         {             res.push_back(pre);             return;         }        for (int i = cur; i + count <= n; i++)         {              pre.push_back(i);              execute(n, i + 1, count, pre);              pre.pop_back();         }    }    vector<vector<int> > combine(int n, int k)    {        res.clear();        vector<int> pre;        execute(n, 1, k, pre);        return res;    }};


0 0
原创粉丝点击