leetcode 40. 組合總和 II 擊敗98%

給定一個數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和爲 target 的組合。

candidates 中的每個數字在每個組合中只能使用一次。

說明:

所有數字(包括目標數)都是正整數。 解集不能包含重複的組合。 示例 1:

輸入: candidates = [10,1,2,7,6,1,5], target = 8, 所求解集爲: [ [1, 7],
[1, 2, 5], [2, 6], [1, 1, 6] ] 示例 2:

輸入: candidates = [2,5,2,1,2], target = 5, 所求解集爲: [ [1,2,2], [5] ]

 static List<List<Integer>> lists;

    public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
        lists = new ArrayList<>();
        LinkedList<Integer> list = new LinkedList<>();
        Arrays.sort(candidates);
        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++) {
            //當x不等於start,說明不是此趟遞歸的起點,這時候跟前面重複的元素可以直接忽略,保證不重複
            if (x != start && candidates[x] == candidates[x - 1]) {
                continue;
            } else 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 + 1);
                list.pollLast();
            }
            //噹噹前元素不符合條件,下次遞歸不需要再使用此元素了,因爲已經窮盡此元素的可能性
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章