Combinations

来源:互联网 发布:c语言a=b>c 编辑:程序博客网 时间:2024/05/01 17:57

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:
这里写图片描述

在leetcode做了很多类似的题目,用递归的思想去解决就可以了。

class Solution {public:    vector<vector<int>> combine(int n, int k) {        _docombine(n,k,1);        return rst;    }private:    vector<vector<int>> rst;    vector<int> temp;    void _docombine(int n,int k,int start){        if(temp.size()==k){            rst.push_back(temp);        }        else{            for(int i=start;i<=n;i++){                temp.push_back(i);                _docombine(n,k,i+1);                temp.pop_back();            }        }    }};
1 0