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

[leetcode] Combinations

时间:2014-12-16 16:50:47      阅读:110      评论:0      收藏:0      [点我收藏+]

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

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],
]
思路:
dfs搜索所有可行解。这里[1,2]和[2,1]算一个解,所以后面的数一定越来越大。
题解:
class Solution {
public:
    vector<vector<int> > res;
    vector<int> tmp;
    void dfs(int n, int k, int t) {
        if(k==0) {
            res.push_back(tmp);
            return;
        }
        for(int i=t+1;i<=n;i++) {
            tmp.push_back(i);
            dfs(n,k-1,i);
            tmp.pop_back();
        }
    }
    vector<vector<int> > combine(int n, int k) {
        if(k==0)
            return res;
        for(int i=1;i<=n;i++) {
            tmp.push_back(i);
            dfs(n,k-1,i);
            tmp.pop_back();
        }
        return res;
    }
};

 

 

[leetcode] Combinations

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

原文地址:http://www.cnblogs.com/jiasaidongqi/p/4167213.html

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