[leetcode] Combinations

来源:互联网 发布:大众 软件 编辑:程序博客网 时间:2024/05/01 18:43

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> > combine(int n, int k) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector<vector<int> > a;        vector<vector<int> > b;        if(n==k){            vector<int> tmp(k);            for(int i=0 ; i<n ; i++)                tmp[i]=i+1;            a.push_back(tmp);            return a;        }        if(k==1){            vector<int> tmp(1);            for(int i=1 ; i<=n ; i++){                tmp[0]=i;                a.push_back(tmp);            }            return a;        }        a=combine(n-1,k-1);        for(int i=0 ; i<a.size() ; i++)            a[i].push_back(n);        b=combine(n-1,k);        a.insert(a.begin(),b.begin(),b.end());        return a;    }};


原创粉丝点击