LeetCode Combinations

来源:互联网 发布:c 串口接收数据 编辑:程序博客网 时间:2024/05/01 05:37

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],]

Reference:

http://blog.csdn.net/maqingli87/article/details/7978785

Solution:

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> > result;        for(int i=1;i<=n;++i){            result.push_back(vector<int>());            result.back().push_back(i);        }        for(int i=1;i<k;++i){            vector<vector<int> > next;            for(int j=0;j<result.size();++j){                vector<int> v=result[j];                for(int x=v.back()+1;x<=n;++x){                    next.push_back(v);                    next.back().push_back(x);                }            }            result=next;        }        return result;    }};

原创粉丝点击