주어진 값들을 더해서(중복선택 가능) target이 되는 조합을 구하라. 결과 조합이 중복될 수 없다. ([2,2,3]과 [3,2,2]는 동일)
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
백트래킹 문제. 잘 몰랐던것.
tmp
임시 벡터를 어떻게 선언해야하는지 [[2,2,3],[2,3,2],[3,2,2],[7]]
이 나오게된다. for (int i = 0; i < candidates.size(); i++)
class Solution {
vector<vector<int>> ret;
vector<int> tmp;
void back_tracking(vector<int> &candidates, int target, int curr)
{
if (target < 0) return;
if (target == 0) {
ret.push_back(tmp);
return;
}
for (int i = curr; i < candidates.size(); i++) {
tmp.push_back(candidates[i]);
back_tracking(candidates, target - candidates[i], i);
tmp.pop_back();
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
back_tracking(candidates, target, 0);
return ret;
}
};