# 039 - Combination Sum

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;
}

#### 【LeetCode】Combination Sum I & II 解题报告

2014-12-16 11:06:12

#### Leetcode: Combination Sum

2013-10-04 16:42:06

#### LeetCode 39. Combination Sum（组合求和）

2016-05-20 10:40:51

#### LeetCode 问题汇总之递归算法

2014-02-27 04:37:35

#### Leetcode全求和问题

2014-02-04 10:29:10

#### LeetCode39——Combination Sum

2015-10-17 21:08:58

#### 回溯详解及其应用：Leetcode 39 combination sum

2017-01-31 16:47:37

#### 回溯法——combination-sum、combination-sum-ii

2016-05-31 13:27:11

#### 377. Combination Sum IV-动态规划

2016-09-22 19:54:56

#### leetcode 39. Combination Sum-回溯算法|递归|非递归

2016-03-15 17:37:26