Skip to content

Commit 4a067a3

Browse files
committed
#254 combination-sum solution
1 parent 277e417 commit 4a067a3

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

combination-sum/sungjinwi.cpp

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
풀이 :
3+
target + 1개의 크기를 가지는 삼중벡터 dp를 만든다
4+
dp[n] = dp[n - candidate]의 각 조합에 candidate를 추가하는 로직으로 쌓아나갈 것이다
5+
dp[n - c]가 [comb1, comb2]일 때 dp[n]은 [comb1.push_back(c), comb2.push_back[2]]
6+
7+
dp[0]은 연산을 위해 빈 이중 벡터로 초기화 ( dp[n] = dp[n - n] = dp[0] --> [[].push_back(n)])
8+
9+
target크기 : T, candidate 갯수 : N
10+
11+
TC : O(T * N)
12+
13+
SC : O(T * N)
14+
*/
15+
16+
#include <vector>
17+
using namespace std;
18+
19+
class Solution {
20+
public:
21+
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
22+
vector<vector<vector<int>>> dp(target + 1);
23+
dp[0] = {{}};
24+
for (int candidate : candidates)
25+
{
26+
for (int num = candidate; num <= target; num++)
27+
{
28+
for (auto& combination : dp[num - candidate])
29+
{
30+
vector<int> new_comb = combination;
31+
new_comb.push_back(candidate);
32+
dp[num].push_back(new_comb);
33+
}
34+
}
35+
}
36+
return dp[target];
37+
}
38+
};

0 commit comments

Comments
 (0)