leetCode(31):Combination Sum III 分类: leetCode 2015-07-07 10:23 163人阅读 评论(0) 收藏

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Ensure that numbers within the set are sorted in ascending order.


Example 1:

Input: k = 3, n = 7

Output:

[[1,2,4]]


Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]
         基本思路:首先确定第一个数,然后在剩余的数列中去寻找其余的数,找到则满足;说到这,自然而然--》递归

void combinationSum(int k,int index,int n,vector<int>& tmp,vector< vector<int> >& vec)
{//k个数据相加为n,数据范围是index~9,tmp用于临时存放数据,vec用于存放返回值
	if(k==1)
	{//还有最后一个名额,如果找不到相符的数据,说明没有满足的情况,需要返回
		for(int i=index;i<=9;++i)
		{
			if(i==n)
			{
				tmp[k-1]=i;
				vec.push_back(tmp);
				break;
			}
		}
	}
	else
	{
		for(int i=index;i<=9;++i)
		{
			tmp[k-1]=i;//反向存放数据,递归
			combinationSum(k-1,i+1,n-i,tmp,vec);
		}
	}
}

vector< vector<int> > combinationSum3(int k, int n)
{
	vector< vector<int> > vec;
	vector<int> tmp;
	for(int i=0;i<k;++i)
	{//初始化
		tmp.push_back(0);
	}
	combinationSum(k,1,n,tmp,vec);
	for(int i=0;i<vec.size();++i)
	{//因为数据是反向存放的,所以还需要一次反转
		reverse(vec[i].begin(),vec[i].end());
	}
	return vec;
}





posted @ 2015-07-07 10:23  朱传林  阅读(171)  评论(0编辑  收藏  举报