Combination Sum II

xiaoxiao2021-02-27  377

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note: All numbers (including target) will be positive integers. The solution set must not contain duplicate combinations. For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8, A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]

方法:DFS

class Solution { private: void find(vector<vector<int>>& res, int index,int temp_sum, const int &target,vector<int>& candidates,vector<int>& buffer){ if(temp_sum == target){ res.push_back(buffer); return; } else if(temp_sum > target){ return; } for(int i = index; i < candidates.size(); ++i){ if(i != index){ if(candidates[i] == candidates[i-1]){ continue; } } buffer.push_back(candidates[i]); find(res,i+1,temp_sum + candidates[i],target,candidates,buffer); buffer.pop_back(); } } public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<vector<int>> res; vector<int> buffer; sort(candidates.begin(),candidates.end()); find(res,0,0,target,candidates,buffer); return res; } };
转载请注明原文地址: https://www.6miu.com/read-801.html

最新回复(0)