[LeetCode]332. Reconstruct Itinerary

本质上是欧拉路径/七桥问题/一笔画问题

1、参考自:

class Solution {
public:
    vector<string> findItinerary(vector<pair<string, string>> tickets) {
        vector<string> res;
        //使用multiset允许同样的值插入多次,且是按序插入的。
        unordered_map<string,multiset<string> > mp;
        for(auto ticket:tickets) //mp[ticket.first].insert(ticket.second);
        {
            mp[ticket.first].insert(ticket.second);
            //cout<< *mp[ticket.first].begin() <<" ";
        }
        //int cnt=0,cnt2=100;
        stack<string> st;
        st.push("JFK");//写成了JKF导致找了半天的bug
        while(!st.empty()){
            string cur=st.top();
            if(mp[cur].empty()){
                res.push_back(cur);
                st.pop();
                //cout<<++cnt;
            }else{
                st.push(*mp[cur].begin());
                mp[cur].erase(mp[cur].begin());
                //cout<<cnt2<<" ";
            }
        }
        
        reverse(res.begin(),res.end());//最先出站的是终点值
        return res;
    }
};    
class Solution {
public:
    vector<string> findItinerary(vector<pair<string, string>> tickets) {
        if(tickets.size()==0) return res;
        for(auto ticket:tickets) mp[ticket.first].insert(ticket.second);
        DFS("JFK");
        reverse(res.begin(),res.end());
        return res;
    }
    
    void DFS(string cur){
        while(!mp[cur].empty()){
        //if(!mp[cur].empty()){
            string next = *mp[cur].begin();
            mp[cur].erase(mp[cur].begin());
            DFS(next);
        }
        res.push_back(cur);
    }
    
    unordered_map<string,multiset<string> > mp;
    vector<string> res;
};

用了if后的错误样例,感觉对递归不够理解。没有搞清楚if和while的区别

Input:[["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]]
Output:["JFK","KUL"]
Expected:["JFK","NRT","JFK","KUL"]
 

猜你喜欢

转载自www.cnblogs.com/bright-mark/p/9626382.html