C++_AC_DFS + Trie (Prefix Tree)


  • 0

    The main problem of this question is how to avoid the duplicate result in our algorithms, so I used Trie to check it. My method may not be the most efficient, but just have a try. LOL
    I also see that lots of people use hash set to solve this problem, thats great!!

    class Node{
    public:
    unordered_map<int, Node*> mp;
    bool isEnd = false;
    };
    
    class Solution {
    public:
    Node node;
    bool find(vector<int>& nums){
        Node* tmp_node = &node;
        for(int i = 0; i < nums.size(); ++i){
            if(tmp_node->mp.find(nums[i]) == tmp_node->mp.end()){
                return false;
            }else{
                tmp_node = tmp_node->mp[nums[i]];
            }
        }
        return tmp_node->isEnd;
    }
    
    void add(vector<int>& nums){
        Node* tmp_node = &node;
        for(int i = 0; i < nums.size(); ++i){
            if(tmp_node->mp.find(nums[i]) != tmp_node->mp.end()){
                tmp_node = tmp_node->mp[nums[i]];
            }else{
                tmp_node->mp[nums[i]] = new Node();
                tmp_node = tmp_node->mp[nums[i]];
            }
        }
        tmp_node->isEnd = true;
    }
    vector<vector<int>> findSubsequences(vector<int>& nums) {
        vector<vector<int>> res;
        if(nums.empty()) return res;
        vector<int> path;
        for(int i = 0; i < nums.size(); ++i){
            path.push_back(nums[i]);
            dfs(nums, res, i + 1, path);
            path.pop_back();
        }
        return res;
    }
    
    void dfs(vector<int>& nums, vector<vector<int>>& res, int pos, vector<int>& path){
        if(pos >= nums.size()) return;
        for(int i = pos; i < nums.size(); ++i){
            if(nums[i] >= path.back()){
                path.push_back(nums[i]);
                if(!find(path)){
                    res.push_back(path);
                    add(path);
                }
                dfs(nums, res, i + 1, path);
                path.pop_back();
            }
        }
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.