首页 > 其他 > 详细

LeetCode OJ:Combinations (排列组合)

时间:2015-10-18 12:43:07      阅读:240      评论:0      收藏:0      [点我收藏+]

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 class Solution {
 2 public:
 3     vector<vector<int>> combine(int n, int k) {
 4         tmp.resize(k);
 5         ret.clear();
 6         dfs(0, k, n, 1);
 7         return ret;
 8     }
 9 
10     void dfs(int depth, int maxDepth, int n, int start)
11     {
12         if(depth == maxDepth){
13             ret.push_back(tmp);
14             return;
15         }
16         for(int i = start ; i <= n; ++i){
17             tmp[depth] = i;
18             dfs(depth + 1, maxDepth, n, i + 1);
19         }
20     }
21 private:
22     vector<vector<int>> ret;
23     vector<int> tmp;
24 };

 

LeetCode OJ:Combinations (排列组合)

原文:http://www.cnblogs.com/-wang-cheng/p/4889187.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!