Combinations 组合

匿名 (未验证) 提交于 2019-12-03 00:34:01

nkk

示例:

输入:输出: [   [2,4],   [3,4],   [2,3],   [1,2],   [1,3],   [1,4], ]

思路:类似于9*9乘法口诀表逐层减一的操作,即如下例子所示(输入n=4,k=2)

1分别对应2,3,4

2分别对应3,4

3对应4

然后把每种组合组合起来即可,这里采用递归的解法,每次都从i=start调用到i=(end-k+1),这里初始化传入的start=1,end=n。当k==0时表示已经不能再分,所以把结果放入res中。

参考代码:

class Solution { public: void combineCore(int start, int end, int k, vector<vector<int>> &res, vector<int> tmp) { 	if ((end - start + 1) < k) { 		return; 	} 	if (k == 0) { 		res.push_back(tmp); 		return; 	} 	for (int i = start; i <= (end - k + 1); i++) { 		tmp.push_back(i); 		combineCore(i + 1, end, k - 1, res, tmp); 		tmp.pop_back(); 	} } vector<vector<int>> combine(int n, int k) { 	vector<vector<int>> res; 	vector<int> tmp; 	combineCore(1, n, k, res, tmp); 	return res; } };




文章来源: Combinations 组合
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!