|
| 1 | +## Description |
| 2 | + |
| 3 | +`queue`를 이용한 BFS로 주어진 `candidates`의 조합을 만듭니다. |
| 4 | + |
| 5 | +조합의 합 S의 크기에 따라 아래와 같이 연산을 진행합니다. |
| 6 | + |
| 7 | +``` |
| 8 | +S < target: 조합에 새로운 수를 추가하여 queue에 다시 push |
| 9 | +S == target: 정답 배열 res에 해당 조합을 push |
| 10 | +S > target: 더 이상 queue에 조합을 등록하지 않음 |
| 11 | +``` |
| 12 | + |
| 13 | +## Big-O |
| 14 | + |
| 15 | +`candidates` 배열의 크기를 `N`, `target`의 크기를 `T`, `candidates` 배열의 원소 중 가장 작은 원소의 크기를 `K`라고 했을 때, |
| 16 | + |
| 17 | +Time complexity: `O(N ^ (T / K))` |
| 18 | + |
| 19 | +- `queue`에 담긴 각 조합들은 최대 `N`개의 새로운 조합들을 만들어 낼 수 있습니다 |
| 20 | +- 이걸 `Tree`에 빗대어 생각해보면 각 `node` 당 `N`개의 자식들을 갖는다고 볼 수 있습니다 |
| 21 | +- `Tree`의 깊이는 `T / K`에 비례합니다 |
| 22 | + |
| 23 | +Space complexity: `O((T / K) * (N ^ (T / K)))` |
| 24 | + |
| 25 | +- `queue`의 크기는 앞서 말한 `Tree`의 `node` 개수만큼 늘어날 수 있습니다 |
| 26 | +- `node`가 지닌 조합 배열의 크기는 `T / K` 까지 커질 수 있습니다 |
| 27 | + |
| 28 | +--- |
| 29 | + |
| 30 | +```cpp |
| 31 | +class Solution { |
| 32 | +public: |
| 33 | + vector<vector<int>> combinationSum(vector<int>& candidates, int target) { |
| 34 | + vector<vector<int>> res; |
| 35 | + queue<pair<int, pair<int, vector<int>>>> q; // {acc, {idx, combination}} |
| 36 | + |
| 37 | + for (int i = 0; i < candidates.size(); i++) { |
| 38 | + int num = candidates[i]; |
| 39 | + |
| 40 | + if (num <= target) { |
| 41 | + vector<int> comb; |
| 42 | + comb.push_back(num); |
| 43 | + q.push({num, {i, comb}}); |
| 44 | + } |
| 45 | + |
| 46 | + } |
| 47 | + |
| 48 | + while (!q.empty()) { |
| 49 | + auto p = q.front(); |
| 50 | + q.pop(); |
| 51 | + |
| 52 | + int acc = p.first, idx = p.second.first; |
| 53 | + auto comb = p.second.second; |
| 54 | + |
| 55 | + if (acc == target) { |
| 56 | + res.push_back(comb); |
| 57 | + } else if (acc < target) { |
| 58 | + for (int i = idx; i < candidates.size(); i++) { |
| 59 | + int num = candidates[i]; |
| 60 | + |
| 61 | + if (acc + num <= target) { |
| 62 | + vector<int> new_comb(comb); |
| 63 | + new_comb.push_back(num); |
| 64 | + q.push({acc + num, {i, new_comb}}); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return res; |
| 71 | + } |
| 72 | +}; |
| 73 | +``` |
0 commit comments