LeetCode(Permutations)

Permutations
深搜:

class Solution {
public:
    vector<vector<int> > permute(vector<int>& num) {
        sort(num.begin(),num.end());
        vector<vector<int> > result;
        vector<int> path;
        dfs(num,result,path);
        return result;
    }
    void dfs(vector<int> &num,vector<vector<int> > &result,vector<int> &path)
    {
        if(path.size()==num.size())
        {
            result.push_back(path);
            return;
        }
        for(int i=0;i<num.size();++i)
        {
            if(find(path.begin(),path.end(),num[i])==path.end())
            {
                path.push_back(num[i]);
                dfs(num,result,path);
                path.pop_back();
            }
        }
    }
};

Permutations II
深搜:

class Solution {
public:
    vector<vector<int> > permuteUnique(vector<int>& num) {
        sort(num.begin(),num.end());
        vector<vector<int>> result;
        vector<int> path; 
        unordered_map<int,int> map;
        for(int i=0;i<num.size();++i)
        {
            if(map.find(num[i])==map.end())map[num[i]]=1;
            else ++map[num[i]];
        }
        dfs(num,result,path,map);
        return result;
    }
    void dfs(vector<int> &num,vector<vector<int> > &result,vector<int> &path,unordered_map<int,int> &map) 
    {
        if(path.size()==num.size())result.push_back(path);
        for(unordered_map<int,int>::iterator i=map.begin();i!=map.end();++i) 
        {
            int cnt=0;
            for(int j=0;j<path.size();++j) 
            {
                if(path[j]==i->first)++cnt;
            }
            if(cnt<i->second)
            {
                path.push_back(i->first);
                dfs(num,result,path,map);
                path.pop_back();
            }
        }
    }
};

你可能感兴趣的:(LeetCode(Permutations))