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

[Leetcode,c++] Combination Sum

by dkswnkk 2021. 11. 7.

๋ฌธ์ œ

 

Combination Sum - 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 {
    map<vector<int>,int>duplicate;

public:
    vector<vector<int>>ans;
    void dfs(vector<int> &candidates,int &target,int sum,vector<int> route){
        if(sum==target){
            sort(route.begin(),route.end());
            if(duplicate[route]==0){
                duplicate[route]++;
                ans.push_back(route);
                return;
            }
        }
        else if(sum>target) return;
        else{
            for(int i=0; i<candidates.size(); i++){
                vector<int>temp(route);
                temp.push_back(candidates[i]);
                dfs(candidates,target,sum+candidates[i],temp);
            }
        }
        return;
    }

    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        dfs(candidates,target,0,{});
        sort(ans.begin(),ans.end());
        return ans;
    }
};

 

ํ’€์ด

๋ฐฑํŠธ๋ž˜ํ‚น์„ ํ™œ์šฉํ•˜์—ฌ dfs๋กœ ๊ณ„์† candidates ๋ฐฐ์—ด์„ ๊นŠ์ด ํƒ์ƒ‰ํ•˜์—ฌ ์ˆซ์ž๋ฅผ ๋”ํ•ด๊ฐ€๋ฉด์„œ target์ˆซ์ž๊ฐ€ ๋œ๋‹ค๋ฉด return ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค.

์œ ์˜ํ•  ์ ์€  {1,1,3}, {1,3,1}์˜ ๊ฒฝ์šฐ ๊ฐ™์€ ๊ฒฝ์šฐ์ด๊ธฐ ๋•Œ๋ฌธ์— ํ•˜๋‚˜๋กœ ์ •๋ ฌ์„ ํ•œ ์ƒํƒœ์ธ {1,1,3} ํ•˜๋‚˜๋กœ ๋ณด์•„์•ผํ•ฉ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ์ €๋Š” ํ•ด์‰ฌ ํ…Œ์ด๋ธ” map์„ ํ™œ์šฉํ•˜์—ฌ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ๋ฅผ ํ•˜์—ฌ ๋™์ผํ•œ ๊ฒฝ์šฐ๋ฅผ ์ œ๊ฑฐํ•ด์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค.

 

ํšŒ๊ณ 

์œ„์˜ ํ’€์ด๋Š” ์‹œ๊ฐ„๊ณผ ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ์••๋„์ ์œผ๋กœ ์ข‹์ง€์•Š์•˜์Šต๋‹ˆ๋‹ค. ๊ทธ๋ž˜์„œ ์ผ์ฃผ์ผ ๋’ค์— ๋‹ค์‹œ ์ƒ๊ฐํ•˜์—ฌ ํ’€์–ด๋ณด์•˜์Šต๋‹ˆ๋‹ค.

์•„๋ž˜๋Š” ๋‹ค์‹œ ์ƒ๊ฐํ•˜์—ฌ ํ’€์ดํ•œ ์ฝ”๋“œ์ž…๋‹ˆ๋‹ค.

class Solution {
public:
    vector<vector<int>>ans;
    
    void dfs(int target,int index,vector<int>& candidates, vector<int>current){
        if(target==0) ans.push_back(current);
        
        for(int i=index; i<candidates.size(); i++){
            if(candidates[i]>target) break;
            current.push_back(candidates[i]);
            dfs(target-candidates[i],i,candidates,current);
            current.pop_back();
        }
    }
        
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(),candidates.end());
        dfs(target,0,candidates,{});
        return ans;
    }
};

for๋ฌธ์„ 0์ด ์•„๋‹ˆ๋ผ index ๋ถ€ํ„ฐ ๋ˆ๋‹ค๋ฉด ๋’ค๋กœ ๋„˜์–ด๊ฐ€๋Š” ์ผ์ด ์—†์–ด์„œ {1,1,3}, {1,3,1}์™€ ๊ฐ™์€ ๊ฒฝ์šฐ๊ฐ€ ์ƒ๊ธฐ์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋˜ํ•œ for๋ฌธ์—์„œ ๊ทธ ๊ฐ’์ด ์œ ํšจํ•œ ๊ฐ’์ธ์ง€ ๋ฏธ๋ฆฌ ๊ฒ€์‚ฌ๋ฅผ ํ•˜์—ฌ ํƒ์ƒ‰์„ ํ•˜๋Š”๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ค„์˜€์Šต๋‹ˆ๋‹ค.

๋Œ“๊ธ€