Solution1:
State Space Tree
Firstly, we find all combitions that contain only one element. For example, if the candidates is [2,3,5], they are three combination: [2], [3], [5]. If the sum of a combination is equal to target, we store this combination as one of the answer. If the sum of a combination is greater than target, we just drop it. If the sum of a combination is less than the target, which means it need to be expended to form a new combination.
Secondly, for all the combinations that need to be expended, we expend them by one element, the index of this element shoud be greator or equle to the index of the last one in this combination. For example, for [3], we can expend it with 3 and 1 to get [3,3] and [3,1]. After expend, we get a new combination, then if the sum of the new combination is equal to target, we store it as one of the outpued element. And if the sum of the new combination is greator then target, just drop it. If the sum of the combination is less than target, which means that it need to be expended further.
Then, keep expening the combinations that need to be expend, until there is none this kind of combinations.
Code:
std::vector<std::vector<int>> combinationSum(std::vector<int>& candidates, int target) {
std::vector<std::vector<int>> result;
const int size = candidates.size();
if (size < 1) {
return result;
}
//std::sort(candidates.begin(), candidates.end());
std::unordered_map<int, int> idxMap;
std::vector<std::vector<int>> NeedToExtend;
// Find combinations of length 1
for (int idx = 0; idx < size; ++idx) {
idxMap[candidates[idx]] = idx;
if (candidates[idx] < target) {
NeedToExtend.push_back(std::vector<int>(1, candidates[idx]));
}
else if (candidates[idx] == target) {
result.push_back(std::vector<int>(1, candidates[idx]));
}
}
// Extend combinations in NeedToExtend.
while (!NeedToExtend.empty()) {
auto NeedToExtendCpy = NeedToExtend;
NeedToExtend.clear();
for (auto& comb : NeedToExtendCpy) {
int lastElem = comb.back();
int lastElemIdx = idxMap[lastElem];
int currSum = 0;
for (auto& it : comb) {
currSum += it;
}
// Add one element to the end of comb
for (int i = lastElemIdx; i < size; ++i) {
if (currSum + candidates[i] == target) {
auto combTmp = comb;
combTmp.push_back(candidates[i]);
result.push_back(combTmp);
}
else if (currSum + candidates[i] < target) {
auto combTmp = comb;
if (combTmp.size() >= 3 && combTmp[0] == 2 && combTmp[1] == 2 && combTmp[2] == 2) {
int cc = 0;
}
combTmp.push_back(candidates[i]);
NeedToExtend.push_back(combTmp);
}
}
}
}
return result;
}
int main()
{
std::vector<int> candidates{ 2,3,1 };// 7, 6, 3, 5,
auto res = combinationSum(candidates, 9);
for (auto& it : res) {
for (auto& val : it) {
std::cout << " " << val << " ";
}
std::cout << std::endl;
}
return 0;
}
Ref: