码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Combinations

时间:2014-12-07 01:16:54      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   os   sp   for   strong   

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

 

递推点:加入i后,下一个加入的元素需要遍历i+1~n

因此可以基于k做递归。

base case: k=1,把所有的元素都逐个加入集合。

 

class Solution {
public:
    vector<vector<int> > combine(int n, int k) {
        vector<vector<int> > result;
        vector<int> cur;
        Helper(result, cur, 1, n, k);
        return result;
    }
    void Helper(vector<vector<int> >& result, vector<int> cur, int begin, int n, int k)
    {
        if(k == 1)
        {
            for(int i = begin; i <= n; i ++)
            {
                cur.push_back(i);
                result.push_back(cur);
                cur.pop_back();
            }
        }
        else
        {
            for(int i = begin; i <= n; i ++)
            {
                cur.push_back(i);
                Helper(result, cur, i+1, n, k-1);
                cur.pop_back();
            }
        }
    }
};

bubuko.com,布布扣

【LeetCode】Combinations

标签:style   blog   http   io   color   os   sp   for   strong   

原文地址:http://www.cnblogs.com/ganganloveu/p/4149003.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!