Problem description: http://oj.leetcode.com/problems/combination-sum-ii/
Basic idea: use recursive approach, remember to avoid duplicate item.
class Solution {
public:
bool isExist(vector<vector<int> > &combinations, vector<int> &item) {
for(auto com: combinations){
if(com.size() == item.size()){
int k;
for(k = ; k < com.size(); k++){
if(com[k] != item[k])
break;
}
if(k == com.size())
return true;
}
}
return false;
}
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<vector<int> > combinations;
std::sort(num.begin(), num.end());
int is_target_equal_to_num = ;
for(int i = ; i < num.size(); i ++){
if(num[i] == target && !is_target_equal_to_num){
is_target_equal_to_num = ;
vector<int> combination(, target);
combinations.push_back(combination);
}else if(num[i] > target) {
break;
}else {
vector<int> sub_num(num.begin() + i + , num.end());
vector<vector<int> > sub_combinations = combinationSum2(sub_num, target - num[i]);
for (auto item : sub_combinations) {
item.insert(item.begin(), num[i]);
if(!isExist(combinations, item))
combinations.push_back(item);
}
}
} return combinations;
}
};