题意

给N个单词表示N个点,和N-1个单词对,表示可以走的路径,求字典序最小的总路径。

 

首先说下这么暴力DFS能过。暴力的我都不敢写= =

class Solution {
public:
    vector<string> findItinerary(vector<vector<string> >& tickets) {
        map<string, vector<string> > mp;

        for (int i = 0; i < tickets.size(); i++) {
            string from = tickets[i][0];
            string to = tickets[i][1];
            if (mp.find(from) == mp.end()) {
                vector<string> v;
                v.push_back(to);
                mp[from] = v;
            } else {
                mp[from].push_back(to);
            }
        }
        for (map<string, vector<string> >::iterator iter = mp.begin(); iter != mp.end(); iter++) {
            sort(iter->second.begin(), iter->second.end());
        }
        vector<string> res;
        string cur = "JFK";
        res.push_back(cur);
        dfs(cur, mp, res, tickets.size());
        return res;
    }

    bool dfs(string cur, map<string, vector<string> > &mp, vector<string> &res, int n) {
        if (res.size() == n + 1) return true;
        if (mp.find(cur) == mp.end()) return false;
        if (mp[cur].size() == 0) return false;
        for (int i = 0; i < mp[cur].size(); i++) {
            string nxt = mp[cur][i];
            res.push_back(nxt);
            mp[cur].erase(mp[cur].begin() + i);
            if (dfs(nxt, mp, res, n)) return true;
            mp[cur].insert(mp[cur].begin() + i, nxt);
            res.pop_back();
        }
        return false;
    }
};
View Code

相关文章:

  • 2021-09-07
  • 2022-12-23
  • 2021-08-19
  • 2022-12-23
  • 2021-04-21
  • 2022-12-23
  • 2021-05-25
  • 2021-06-22
猜你喜欢
  • 2021-07-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-22
  • 2022-12-23
  • 2022-03-06
相关资源
相似解决方案