现在的位置: 首页 > 综合 > 正文

Combinations

2017年12月23日 ⁄ 综合 ⁄ 共 552字 ⁄ 字号 评论关闭

题目描述如下:

 

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],
]
 
一个简单的递归就可以了:
class Solution {
public:
	int n;
	int k;
   	vector<vector<int> > combine(int tn,int k)
	{
     		n=tn;
		vector<vector<int> > ans;
		vector<int> tmp;
		_combineAll(0,k,ans,tmp);
		return ans;
	}

	void _combineAll(int cur,int need,vector<vector<int> >& ans,vector<int>& tmp)
	{
		if (need==0)
		{
			ans.push_back(tmp);
			return;
		}
		if (n-cur<need)
			return;
		tmp.push_back(cur+1);
		_combineAll(cur+1,need-1,ans,tmp);
		tmp.pop_back();
		_combineAll(cur+1,need,ans,tmp);
	}
};

【上篇】
【下篇】

抱歉!评论已关闭.