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

Leetcode dfs Combinations

时间:2014-09-01 01:40:32      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   os   io   ar   for   art   div   

Combinations

 Total Accepted: 18327 Total Submissions: 60479My Submissions

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



题意:给定两个数字 n 和 k,给出从1...n数字中取 k个的所有可能组合
思路:dfs
递归的深度为 k,第 i 层的第j个节点有  n - i - j 个选择分支
复杂度:时间 O(n^k),空间O(k)

vector<vector<int> > res;
int nn, kk;
void dfs(int cur, int start, vector<int> &path){
	if(cur == kk ){
		res.push_back(path);
	}
	for(int i = start; i <= nn; i++){
		path.push_back(i);
		dfs(cur + 1, i + 1, path);
		path.pop_back();
	}
}


vector<vector<int> > combine(int n, int k){
	nn = n, kk = k;
	vector<int> path;
	dfs(0, 1, path);
	return res;
}


Leetcode dfs Combinations

标签:style   http   color   os   io   ar   for   art   div   

原文地址:http://blog.csdn.net/zhengsenlie/article/details/38968227

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