๋ฌธ์
์ฝ๋
class Solution {
public:
void dfs(int index, vector<int>& candidates, int target, vector<vector<int>>& ans, vector<int>¤t){
if(target==0){
ans.push_back(current);
return;
}
for(int i=index; i<candidates.size(); i++){
if(i>index && candidates[i]==candidates[i-1]) continue;
if(candidates[i]>target) break;
current.push_back(candidates[i]);
dfs(i+1,candidates,target-candidates[i],ans,current);
current.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<int>current;
vector<vector<int>>ans;
dfs(0, candidates, target, ans, current);
return ans;
}
};
ํ์ด
์ด์ Combination Sum I ๋ฌธ์ ์ ์ ๋ ฅ์ ์ค๋ณต๋ ๊ฐ์ด ๋ค์ด์จ๋ค๋ ๊ฒ ๋นผ๊ณ ๋ ๋์ผํ ๋ฌธ์ ์ ๋๋ค.
candidates = {1,1,2,3} , target = 3์ผ ๋ ์ค๋ณต์ฒ๋ฆฌ๋ฅผ ํด์ฃผ์ง ์์ผ๋ฉด [1,2] , [1,2] ๊ฐ์ด ๋ ์์ด ์๊ธฐ๊ธฐ ๋๋ฌธ์
if(i>index && candidates[i]==candidates[i-1]) continue;
์์ ๊ฐ์ ์กฐ๊ฑด์ ์ถ๊ฐํด์ฃผ์ด ์ค๋ณต์ ์ฒ๋ฆฌํด์ฃผ์์ต๋๋ค.
๋ง์ฝ ์ ์กฐ๊ฑด๋ฌธ์ผ๋ก ์ฒ๋ฆฌํด์ฃผ์ง ์๊ณ ์๋์ ๊ฐ์ด ์ง ๋ค๋ฉด ์๊ฐ ์ด๊ณผ๊ฐ ๋น๋๋ค.
class Solution {
public:
map<vector<int>,int>visited;
void dfs(int index, vector<int>& candidates, int target, vector<vector<int>>& ans, vector<int>¤t){
if(target==0){
if(visited[current]==0){
ans.push_back(current);
visited[current]=1;
}
return;
}
for(int i=index; i<candidates.size(); i++){
// if(i>index && candidates[i]==candidates[i-1]) continue;
if(candidates[i]>target) break;
current.push_back(candidates[i]);
dfs(i+1,candidates,target-candidates[i],ans,current);
current.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<int>current;
vector<vector<int>>ans;
dfs(0, candidates, target, ans, current);
return ans;
}
};
'Algorithm ๐ง๐ปโ๐ป > Leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Leetcode,c++] Network Delay Time (0) | 2021.11.22 |
---|---|
[Leetcode,c++] Valid Anagram (0) | 2021.11.20 |
[Leetcode,c++] Single Number (0) | 2021.11.19 |
[Leetcode,c++] Subsets II (0) | 2021.11.15 |
[Leetcode,c++] Rotate Image (0) | 2021.11.15 |
[Leetcode,c++] Permutations II (0) | 2021.11.15 |
๋๊ธ