Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
배열에 있는 숫자의 합으로 target을 조합하는 경우의 수 리턴하기
배열내에서 숫자가 겹치는 것은 허용되나 서로 다른 배열끼리는 겹쳐선 안된다.
Example 1:
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.
Example 2:
Input: candidates = [2,3,5], target = 8 Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3:
Input: candidates = [2], target = 1 Output: []
Example 4:
Input: candidates = [1], target = 1 Output: [[1]]
Example 5:
Input: candidates = [1], target = 2 Output: [[1,1]]
Constraints:
- 1 <= candidates.length <= 30
- 1 <= candidates[i] <= 200
- All elements of candidates are distinct.
- 1 <= target <= 500
문제 풀이:
- 백트래킹 이용하기
- 여태 저장한 합이 target과 같으면 정답에 푸쉬하고 리턴한다.
- 타겟보다 크면 문제의 조건상(모두 양수인 배열) 더 이상 진행해도 target값이 될 수 없으므로 종료
- 배열끼리 겹치면 안되므로 시작점을 저장한다. nextIdx
-> 시작점을 저장하여 nextIdx와 같거나 그 이후의 숫자들만 푸쉬하도록 한다.
class Solution {
public:
vector<vector<int>> result;
void BackTracking(int sum, vector<int>& v, vector<int>& candidates, int& target, int nextIdx){
if(sum > target){
return;
}
if(sum == target){
result.push_back(v);
return;
}
for(int i=nextIdx; i<candidates.size(); i++){
v.push_back(candidates[i]);
BackTracking(sum + candidates[i], v, candidates, target, i);
v.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<int> tmp;
BackTracking(0, tmp, candidates, target,0);
return result;
}
};
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 152] Maximum Product Subarray (0) | 2020.10.26 |
---|---|
[leetcode 198] House Robber (0) | 2020.10.25 |
[leetcode 105] Construct Binary Tree from Preorder and Inorder Traversal (0) | 2020.10.24 |
[leetcode 78] Subsets (0) | 2020.10.24 |
[leetcode 104] Maximum Depth of Binary Tree (0) | 2020.10.23 |
댓글