Combination Sum
Description
Given a set of candidate numbers candidates and a target number target. Find all unique combinations in candidates where the numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
All numbers (including target) will be positive integers.
Numbers in a combination a1, a2, … , ak must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak)
Different combinations can be in any order.
The solution set must not contain duplicate combinations.
public class Solution {
/**
* @param candidates: A list of integers
* @param target: An integer
* @return: A list of lists of integers
*/
public List<List<Integer>> combinationSum(int[] candidates, int target) {
// write your code here
List<List<Integer>> results = new ArrayList<>() ;
if(candidates == null){
return null ;
}
if(candidates.length == 0){
return results ;
}
Arrays.sort(candidates);
List<Integer> subset = new ArrayList<Integer>() ;
helper(results , 0 , target , subset , candidates) ;
return results ;
}
public void helper(List<List<Integer>> results , int start , int remintarget , List<Integer> subset , int[] candidates){
if(remintarget == 0){
results.add(new ArrayList<Integer>(subset)) ;
return ;
}
for(int i = start ; i < candidates.length ; i++ ){
if(remintarget < candidates[i]){
break ;
}
if(i >0 && candidates[i] == candidates[i-1]){
continue ;
}
subset.add(candidates[i]);
helper(results, i , remintarget-candidates[i] , subset , candidates);
subset.remove(subset.size()-1);
}
}
}
该博客介绍了一种解决组合总和问题的方法,即给定一组候选数字和一个目标数字,找出所有可能的不重复组合,使得候选数字的和等于目标数字。文章通过一个名为`Solution`的类实现,主要包含`combinationSum`和`helper`两个方法。`combinationSum`方法首先对输入的候选数字进行排序,并初始化结果列表和子集。`helper`方法采用回溯法递归地搜索所有可能的组合。当剩余目标为0时,将当前子集添加到结果中。整个过程确保了数字的非降序排列和结果的唯一性。
90

被折叠的 条评论
为什么被折叠?



