Untitled
/*Problem Statement : Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations.*/ class Solution { public: int sum(vector<int>& subset){ int ans=0; for (int i = 0; i<subset.size();i++){ ans =ans + subset[i]; } return ans; } void calcSub(vector<int>& array,vector<vector<int>>& res,vector<int> subset,int index,int target){ if (sum(subset) == target){ res.push_back(subset); } for (int i = index;i<array.size();i++){ subset.push_back(array[i]); calcSub(array,res,subset,i+1,target); subset.pop_back(); } } vector<vector<int>> subset(vector<int>& array,int target){ vector<int> subset; int index = 0; vector<vector<int>> res; calcSub(array,res,subset,index,target); return res; } vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { return subset(candidates,target); } };
Leave a Comment