leetcode[77]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],
]
class Solution {
public:
void combination(vector<vector<int>> &res,vector<int> &temp, int from, int to, int k)
{
    if (k==0)
    {
        res.push_back(temp);
        return;
    }
    else
    {
        if(from>to)return;
        else
        {
            temp.push_back(from);
            combination(res,temp,from+1,to,k-1);
            temp.pop_back();
            combination(res,temp,from+1,to,k);
        }
    }
    return;
}
vector<vector<int> > combine(int n, int k) 
{
    vector<vector<int>> res;
    res.clear();
    vector<int> temp;
    temp.clear();
    combination(res,temp,1,n,k);
    return res;
}
};

 

posted @ 2015-02-09 14:17  Vae永Silence  阅读(145)  评论(0编辑  收藏  举报