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

[Leetcode,c++] Subsets II

by dkswnkk 2021. 11. 15.

๋ฌธ์ œ

 

Subsets 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:
    map<vector<int>,int>visited;
    vector<vector<int>>ans;

    void dfs(int num, vector<int>&nums,vector<int>current){

        sort(current.begin(),current.end());
        if(!visited[current]){
            ans.push_back(current);
            visited[current]=1;
        }

        if(num>nums.size()) return;

        for(int i=num; i<nums.size(); i++){
            vector<int>temp=current;
            temp.push_back(nums[i]);
            dfs(i+1,nums,temp);
        }
    }

    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        for(int i=0; i<nums.size(); i++){
            dfs(i,nums,{});
        }
        sort(ans.begin(),ans.end());
        return ans;
    }
};

 

ํ’€์ด

backtraking ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

inp: [4,4,4,1,4]
out: [[],[1],[1,4],[1,4,4],[1,4,4,4],[1,4,4,4,4],[4],[4,4],[4,4,4],[4,4,4,4]]

์œ„ ์ฒ˜๋Ÿผ ์ •๋ ฌ ๋œ ์ฑ„๋กœ ์ถœ๋ ฅํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ •๋ ฌ์„ ํ•ด์ฃผ๋Š”๊ฒŒ ๊ด€๊ฑด์ด๋ฉฐ, ์ €๋Š” map<vector<int>,int>visited ์„ ํ†ตํ•ด ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ๋ฅผ ํ•˜์—ฌ ์ค‘๋ณต์ฒ˜๋ฆฌ๋ฅผ ์ œ๊ฑฐํ–ˆ์Šต๋‹ˆ๋‹ค.

 

'Algorithm ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป > Leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Leetcode,c++] Valid Anagram  (0) 2021.11.20
[Leetcode,c++] Single Number  (0) 2021.11.19
[Leetcode,c++] Combination Sum II  (0) 2021.11.16
[Leetcode,c++] Rotate Image  (0) 2021.11.15
[Leetcode,c++] Permutations II  (0) 2021.11.15
[Leetcode,c++] Roman to Integer  (0) 2021.11.15

๋Œ“๊ธ€