給定一個無重複元素的數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和爲 target
的組合。candidates 中的數字可以無限制重複被選取。
說明:
所有數字(包括 target)都是正整數。 解集不能包含重複的組合。 示例 1:
輸入: candidates = [2,3,6,7], target = 7, 所求解集爲: [ [7], [2,2,3] ] 示例
2:輸入: candidates = [2,3,5], target = 8, 所求解集爲: [ [2,2,2,2], [2,3,3],
[3,5] ]
static List<List<Integer>> lists;
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
lists = new ArrayList<>();
LinkedList<Integer> list = new LinkedList<>();
search(list, candidates, target, 0);
return lists;
}
/**
* 遞歸搜索,linkedlist保存當前元素組成,target表示剩餘值,start表示當前待選數組起始偏移量
* */
public static void search(LinkedList<Integer> list, int[] candidates, int target, int start) {
for (int x = start; x < candidates.length; x++) {
if (candidates[x] == target) {
list.addLast(candidates[x]);
lists.add(new ArrayList<>(list));
list.pollLast();
} else if (candidates[x] < target) {
list.addLast(candidates[x]);
search(list, candidates, target - candidates[x], x);
list.pollLast();
}
//噹噹前元素不符合條件,下次遞歸不需要再使用此元素了,因爲已經窮盡此元素的可能性
}
}