关闭

039 - Combination Sum

130人阅读 评论(0) 收藏 举报
分类:

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]

[2, 2, 3]


给定一个数列,给定一个target,找出数列中的几个数,这几个数的和为target,

数列中的数可以重复使用

先排序,去除重复的数字,再递归求值,要注意,下一个取出来的数不能比之前取出来的数小,用left变量来判断

int mycompar(const void *a, const void *b)
{
	int *x = (int *)a;
	int *y = (int *)b;
	if (*x > *y) return 1;
	return *x == *y? 0 : -1;
}

void dofun(int *nlist, int nsize, int target, int **ret, int *col, int *retsize, int *tmp, int *tmpsize)
{
	int i;

	if (target==0) {
		//tmp[(*tmpsize)++] = nlist[0];
		int *line = (int *)calloc(sizeof(int), *tmpsize);
		col[*retsize] = *tmpsize;
		memcpy(line, tmp, *tmpsize * sizeof(int));
		ret[*retsize] = line;
		(*retsize)++;
		return;
	}
	if (target < nlist[0]) return;
	for (i = 0; i < nsize; i++) {
		tmp[(*tmpsize)++] = nlist[i];
		dofun(nlist + i, nsize - i, target - nlist[i], ret, col, retsize, tmp, tmpsize);
		(*tmpsize)--;
	}
}

int **combinationSum(int *nlist, int nsize, int target, int **col, int *retsize)
{
	qsort(nlist, nsize, sizeof(int), mycompar);
	int i, k=0, past=-1;
	for (i = 0; i < nsize; i++) {
		if (nlist[i] != past)
			nlist[k++] = nlist[i];
		past = nlist[i];
	}
	nsize = k;

	int **ret = (int **)calloc(sizeof(int *), 8192);
	*col = (int *)calloc(sizeof(int), 8192);
	int tmp[8192] = {0};
	int tmpsize = 0;
	int sum = 0;
	dofun(nlist, nsize, target, ret, *col, retsize, tmp, &tmpsize);
	return ret;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:26586次
    • 积分:1487
    • 等级:
    • 排名:千里之外
    • 原创:124篇
    • 转载:10篇
    • 译文:0篇
    • 评论:0条
    博客专栏