Combination Sum II

题目链接

思路: 先排序,再 DFS 回溯时进行去重。

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end()); 
        vector<vector<int> > res; 
        vector<int> temp; 
        DFS(candidates, target, res, temp, 0); 
        return res; 
    }
    
private:
    void DFS(vector<int>& candidates, int target, vector<vector<int>>& res, vector<int>& temp, int step)
    {
        if(target == 0)
        {
            res.push_back(temp); 
            return; 
        }
        for(int i = step; i != candidates.size() && target >= candidates[i]; ++i)    
        {
            if(i == step || candidates[i]!=candidates[i-1])    // 去重,并且利用了 || 的短路计算规则。 
            {
                temp.push_back(candidates[i]); 
                DFS(candidates, target-candidates[i], res, temp, i+1);  // 注意这里是:i+1 
                temp.pop_back(); 
            }
        }
    }
};
posted @ 2017-04-23 20:19  草滩小恪  阅读(155)  评论(0编辑  收藏  举报