package offer;
import java.util.LinkedList;
import java.util.List;
public class 允许重复选择元素的组合 {
public static void main(String[] args) {
int [] nums = {2,3,6,7};
System.out.println(combinationSum(nums,7));
}
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new LinkedList<>();
LinkedList<Integer> con = new LinkedList<>();
helper(candidates,target,0,con,result);
return result;
}
private static void helper(int[] candidates,int target,int i,LinkedList<Integer> con,List<List<Integer>> result){
if(target==0){
result.add(new LinkedList<>(con));
}else if(target>0&&i<candidates.length){
helper(candidates,target,i+1,con,result);
con.add(candidates[i]);
helper(candidates,target-candidates[i],i,con,result);
con.removeLast();
}
}
}
因为允许重复选择,所以当选择过后 i不用加一