Problem Statement could be found @ https://leetcode.com/problems/combination-sum-ii/
Approach-
1. Sort the number.This will give an ordering to the numbers
2. Start with a number and keep on adding next number
A. If their sum is more than target then this is invalid combination, so don't add any more numbers.
B. If the sum is less than target then more numbers could be added
C. If the sum is equal to target, then we have our answer. But We need to be careful not to try same combination again.
Code Snippet-
class Solution {
vector<vector<int>> retvec;
public:
void helper(vector<int> &nums, int index, int target, vector<int> &temp, int sum){
if (sum == target){
retvec.push_back(temp);
return;
}
for (int i=index;i< nums.size();i++){
if ((i > index) && (nums[i]==nums[i-1])){
continue;
}
if ((nums[i]+sum) > target){
return;
}
temp.push_back(nums[i]);
helper(nums, i+1, target, temp, sum+nums[i]);
temp.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<int> temp;
int sum=0;
helper(nums,0, target, temp, sum);
return retvec;
}
};
Approach-
1. Sort the number.This will give an ordering to the numbers
2. Start with a number and keep on adding next number
A. If their sum is more than target then this is invalid combination, so don't add any more numbers.
B. If the sum is less than target then more numbers could be added
C. If the sum is equal to target, then we have our answer. But We need to be careful not to try same combination again.
Code Snippet-
class Solution {
vector<vector<int>> retvec;
public:
void helper(vector<int> &nums, int index, int target, vector<int> &temp, int sum){
if (sum == target){
retvec.push_back(temp);
return;
}
for (int i=index;i< nums.size();i++){
if ((i > index) && (nums[i]==nums[i-1])){
continue;
}
if ((nums[i]+sum) > target){
return;
}
temp.push_back(nums[i]);
helper(nums, i+1, target, temp, sum+nums[i]);
temp.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<int> temp;
int sum=0;
helper(nums,0, target, temp, sum);
return retvec;
}
};