leetcode-332-Reconstruct Itinerary

来源:互联网 发布:js设置全局cookie 编辑:程序博客网 时间:2024/05/20 06:53

这道题考的是DFS、有向图、欧拉路径(一笔画问题)、Hierholzer’s 算法。

思路:把问题抽象成一个图,求一笔画路径,还要保持最小序输出,所以应该用multiset存储一个起点的目的地。想到map

class Solution {public:    void dfs(string airport) {        while (map1[airport].size()) {            string temp = *map1[airport].begin();            map1[airport].erase(map1[airport].begin());            dfs(temp);        }        ret.push_back(airport);    }    map<string, multiset<string>> map1;    vector<string> ret;    vector<string> findItinerary(vector<pair<string, string>> tickets) {        for (auto i : tickets) {            map1[i.first].insert(i.second);        }        dfs("JFK");        return vector<string>(ret.rbegin(), ret.rend());    }};

另外,priority_queue也是可以的:
C++代码:

class Solution {public:    void dfs(string airport) {        while (map1[airport].size()) {            string temp = (map1[airport]).top();            map1[airport].pop();            dfs(temp);        }        ret.push_back(airport);    }    map<string, priority_queue<string,vector<string>,greater<string>>> map1;    vector<string> ret;    vector<string> findItinerary(vector<pair<string, string>> tickets) {        for (auto i : tickets) {            map1[i.first].push(i.second);        }        dfs("JFK");        return vector<string>(ret.rbegin(), ret.rend());    }};
0 0
原创粉丝点击