# leetCode 39.Combination Sum(组合总和) 解题思路和方法

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, a1 ≤ a2 ≤ … ≤ 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]

public class Solution {
public List<List<Integer>> combinationSum(int[] a, int t) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
Arrays.sort(a);//数组排序
//各种特殊情况
if(a.length == 0 || a[0] > t)
return list;

int len = 0;
for(int i = 0; i< a.length;i++){
if(a[i] == t){
List<Integer> al = new ArrayList<Integer>();
}
}else if(a[i] < t){//只要比target小的值，大的值肯定不满足，排除
a[len++] = a[i];//新数组
}
}
//只存在a[0] < target 或 a[0] > target
if(a[0] > t)//肯定已没有符合要求的组合
return list;
//a[0] < target

for(int i = 0; i < len; i++){//循环搜索符合要求的数字组合
int[] b = Arrays.copyOfRange(a, i, len);//不含>=t数据的新数组
if(a[i] > t)//如果a[i]，肯定以后的数据已不符合，返回
break;
//相等于已经有了一个值a[0]了
List<List<Integer>> newList = new ArrayList<List<Integer>>();
newList = combinationSum(b,t-a[i]);
if(newList.size() > 0){//里面有符合要求的数据
for(int j = 0; j < newList.size();j++){
Collections.sort(newList.get(j));//排序
}
}
}
return list;
}
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：leetCode 39.Combination Sum(组合总和) 解题思路和方法 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)