要求:
给一个正整数的数组,再给一个target整数,找出数组里的值排列组合,加起来等于target的所有组合。
例如,输入
candidates = [2,3,6,7], target = 7,
输出
[ [7], [2,2,3] ]
注:1,所给数组中的值不重复,2,数组中的值可以重复使用。
基本思路:
1,先给数组值排序
2,从数组中最大值开始循环,用target值减目标值,进行递归,
3,主要思想用到回溯算法,即不管对不对,先往这条路上走,对的话记录并返回,不对的话,返回。
代码一:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result=new ArrayList<>();
int length=candidates.length;
for (int i = length-1; i >-1; i--) {
LinkedList<Integer> list=new LinkedList();
getSumValue(i,target,list,result,candidates);
}
return result;
}
private void getSumValue(int currentIndex,int preValue,LinkedList<Integer> list,List<List<Integer>> resultList,int[] candidates){
int currentValue=candidates[currentIndex];
int tagValue=preValue-currentValue;
list.push(currentValue);
if(tagValue==0){
resultList.add(new ArrayList<>(list));
}else if(tagValue>0){
for (int i = currentIndex; i >-1 ; i--) {
getSumValue(i,tagValue,list,resultList,candidates);
list.pop();
}
}
}
}
结果
代码二:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result=new ArrayList<>();
getSumValue(candidates.length-1,target,new ArrayList<>(),result,candidates);
return result;
}
private void getSumValue(int currentIndex,int preValue,List<Integer> list,List<List<Integer>> resultList,int[] candidates){
for (int i = currentIndex; i >-1; i--) {
int currentValue=candidates[i];
int tagValue=preValue-currentValue;
if(tagValue==0){
list.add(currentValue);
resultList.add(new ArrayList<>(list));
list.remove(list.size()-1);
}else if(tagValue>0){
list.add(currentValue);
getSumValue(i,tagValue,list,resultList,candidates);
list.remove(list.size()-1);
}
}
}
}
结果: