๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/Leetcode

[Leetcode,c++] Combination Sum II

by dkswnkk 2021. 11. 16.

๋ฌธ์ œ

 

Combination Sum II - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

์ฝ”๋“œ

class Solution {
public:
    void dfs(int index, vector<int>& candidates, int target, vector<vector<int>>& ans, vector<int>&current){

        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>&current){
        
        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

๋Œ“๊ธ€