leetcode 40

与上题类似,用if(i>start&&candidates[i]==candidates[i-1]) continue 来去掉重复的结果。例中 1 2 2 2 5 ,将1 push 将第二个2push 第三个2 因为与第二个2相同则不push 排除了相同的结果。

void combinationSum2DFS(vector> &res,vector &out,vector& candidates,int target,int start){
        if(target<0)
            return;
        else if(target==0)
            res.push_back(out);
        else
        {
            for(int i=start;istart&&candidates[i]==candidates[i-1]) continue;
                out.push_back(candidates[i]);
                combinationSum2DFS(res,out,candidates,target-candidates[i],i+1);
                out.pop_back();
            }
        }
    }
    vector> combinationSum2(vector& candidates, int target) {
        vector> res;
        vector out;
        sort(candidates.begin(),candidates.end());
        combinationSum2DFS(res,out,candidates,target,0);
        return res;
    }

 

你可能感兴趣的:(Leetcode)