1. 程式人生 > >(LeetCode 40) 組合總和 II [DFS: 去重]

(LeetCode 40) 組合總和 II [DFS: 去重]

40. 組合總和 II 給定一個數組 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] ]

分析: 此題是這一題的升級版。https://blog.csdn.net/STILLxjy/article/details/83627703 其實就是多添加了一個去重的條件。由於此題中存在重複的元素,並且每個數字只能使用一次,所以: 1:將‘組合總和’中的used = i, 變為i + 1。即下一次只能新增其後面的數字。 2:為了保證不出現[1,2,5],[1,2,5]這樣重複的答案,新增約束:排序後,對於相同的數字而言,只有當它前面的,與它相等的數字已經被添加了,才能新增這個數字。我們使用int f[] 陣列來標記每個數字被新增的情況。

AC程式碼:

class Solution {
public:
    int n;
    int f[100000];
    
    void dfs(vector<int> cur, int sum, int used, vector<vector<int>>& ans,vector<int>& candidates,int target)
    {
        if(sum > target) return;
        if(sum == target)
        {
            ans.push_back(cur);
            return;
        }
        for(int i=used;i<n;i++)
        {
            if(i == 0 || (candidates[i-1] != candidates[i]) || f[i-1] == 1)
            {
                vector<int> t = cur;
                t.push_back(candidates[i]);
                f[i] = 1;
                dfs(t,sum+candidates[i],i+1,ans,candidates,target);
                f[i] = 0;
                if(sum+candidates[i] > target) break;
            }
            
        }
    }
    
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(),candidates.end());
        vector<vector<int>> ans;
        vector<int> cur;
        n = candidates.size();
        memset(f,0,sizeof(f));
        dfs(cur,0,0,ans,candidates,target);
        return ans;
    }
};