From 6eca5f9a839f6a1da1d3fdc9761b43e432861f5d Mon Sep 17 00:00:00 2001 From: "naveen_ky@hotmail.com" <696787nit> Date: Fri, 2 Oct 2020 23:44:39 +0530 Subject: [PATCH] interviewbit: combinational sum2 Updated the exisitng code more optimise version. The exisiting one is gettin time out on leetcode for similar problem. https://leetcode.com/problems/combination-sum-ii/ --- Backtracking/CombinationSumII.cpp | 58 ++++++++++++------------------- 1 file changed, 22 insertions(+), 36 deletions(-) diff --git a/Backtracking/CombinationSumII.cpp b/Backtracking/CombinationSumII.cpp index 273ca7d..87d9151 100644 --- a/Backtracking/CombinationSumII.cpp +++ b/Backtracking/CombinationSumII.cpp @@ -1,44 +1,30 @@ -void make(vector& A, int curr, int currSum, int sum, vector temp, vector >& ans, map, bool>& m){ - if(currSum > sum){ - return; - } - else if(currSum == sum){ - if(m.find(temp) == m.end()){ - m[temp] = true; - ans.push_back(temp); - } +void back_track(vector> &ans, vector &combination, vector& candidates, int start, int target) { + if (target == 0) { + ans.push_back(combination); return; } - - for(int i = curr; i < A.size(); i++){ - vector t(temp); - t.push_back(A[i]); - make(A, i+1, currSum+A[i], sum, t, ans, m); + + for ( int i = start; i < candidates.size(); i++) { + if ((target - candidates[i]) < 0) + return; + if (candidates[i] <= target) { + combination.push_back(candidates[i]); + back_track(ans, combination, candidates, i + 1, target - candidates[i]); + combination.pop_back(); + while(i+1 > Solution::combinationSum(vector &A, int B) { - // Do not write main() function. - // Do not read input, instead use the arguments to the function. - // Do not print the output, instead return values as specified - // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details - - vector > ans; - - int n = A.size(); - - if(A.size() == 0){ - return ans; - } - + vector> ans; + vector combination; + vector::iterator ip; + sort(A.begin(), A.end()); - map, bool> m; + back_track(ans, combination, A, 0, B); - for(int i = 0; i < n; i++){ - vector temp; - temp.push_back(A[i]); - make(A, i+1, A[i], B, temp, ans, m); - } - - return ans; -} + return ans; +} \ No newline at end of file