1. 程式人生 > >乘風破浪:LeetCode真題_040_Combination Sum II

乘風破浪:LeetCode真題_040_Combination Sum II

urn private turn 技術 ons java 使用 bin image

乘風破浪:LeetCode真題_040_Combination Sum II

一、前言

這次和上次的區別是元素不能重復使用了,這也簡單,每一次去掉使用過的元素即可。

二、Combination Sum II

2.1 問題

技術分享圖片

技術分享圖片

2.2 分析與解決

通過分析我們可以知道使用遞歸就可以解決問題,並且這次我們從頭遍歷一次就不會出現多次使用某一個元素了。

class Solution {
    List<List<Integer>> ans;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        ans = new ArrayList<>();
        track(candidates, 0, target, new ArrayList<>());
        return ans;
    }

    private void track(int[] candidates, int index, int target, List<Integer> list) {
        if (target == 0) {
            ans.add(list);
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (target < candidates[i] || (i > index && candidates[i] == candidates[i - 1]))//重要
continue; List<Integer> temp = new ArrayList<>(list); temp.add(candidates[i]); track(candidates, i + 1, target - candidates[i], temp); } } }

技術分享圖片

如果這裏沒有(i > index && candidates[i] == candidates[i - 1])判斷的話,就會造成重復的結果,究其原因是如果兩個相同,之前的添加之後會進入到下一個遞歸裏面運行了,而我們這個時候如果不過濾再次運行就會重復。

三、總結

遞歸在我們的程序中用的非常多,一定要熟練深刻掌握。

乘風破浪:LeetCode真題_040_Combination Sum II