乘風破浪:LeetCode真題_040_Combination Sum II

 乘風破浪:LeetCode真題_040_Combination Sum II

1、前言

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

2、Combination Sum II

2.1 問題

2.2 分析與解決

    經過分析咱們能夠知道使用遞歸就能夠解決問題,而且此次咱們從頭遍歷一次就不會出現屢次使用某一個元素了。spa

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])判斷的話,就會形成重複的結果,究其緣由是若是兩個相同,以前的添加以後會進入到下一個遞歸裏面運行了,而咱們這個時候若是不過濾再次運行就會重複。blog

3、總結

    遞歸在咱們的程序中用的很是多,必定要熟練深入掌握。遞歸

相關文章
相關標籤/搜索