399. Evaluate Division

在這裏插入圖片描述

這題一開始想法有些問題,而後糾正後,寫的時候反覆出現各類小問題,這些都是能夠避免並且在面試中會減分的,真想扇本身一巴掌。。web

由於這裏我在dfs的過程當中只用了乘法,那麼它的source和target就分別是被除數和除數,順序不能亂。可是在計算這種狀況:給出a/b, a/c,要求b/c,若是說我只把b和c壓入a的鄰接表裏面,這樣就得不出正確答案;須要再反一下,把a壓入b的鄰接表,把a壓入c的鄰接表,這樣才能由b找到a,再由a找到c。一開始忽略了這種狀況,致使了錯誤。面試

class Solution {
public:
    vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
        unordered_map<string, vector<string>> adjs;
        map<pair<string, string>, double> valueMap;
        for (int i = 0; i < equations.size(); ++i) {
            auto& source = equations[i][0];
            auto& target = equations[i][1];
            adjs[source].push_back(target);
            valueMap[make_pair(source, target)] = values[i];
            adjs[target].push_back(source);
            valueMap[make_pair(target, source)] = 1.0/values[i];
        }
        unordered_set<string> visited;
        vector<double> ret;
        for (auto& query : queries) {
            auto& source = query[0];
            auto& target = query[1];
            if (adjs.find(source) == adjs.end()) {
                ret.push_back(-1.0);
                continue;
            }
            if (source == target) {
                ret.push_back(1.0);
                continue;
            }
            visited.clear();
            double v = dfs(adjs, valueMap, source, target, visited);
            if (v != 0) {
                ret.push_back(v);
                continue;
            }
            visited.clear();
            v = dfs(adjs, valueMap, target, source, visited);
            ret.push_back(v == 0.0? -1.0 : 1.0/v);
        }
        return ret;
    }
private:
    double dfs(unordered_map<string, vector<string>>& adjs, map<pair<string, string>, double>& valueMap, string source, string target, unordered_set<string>& visited) {
        if (adjs.find(source) == adjs.end())
            return 0.0;
        auto& vec = adjs[source];
        for(auto& str : vec) {
            if (str == target)
                return valueMap[make_pair(source, target)];
            if (visited.find(str) != visited.end())
                continue;
            visited.insert(str);
            double v = dfs(adjs, valueMap, str, target, visited);
            visited.erase(str);
            if (v != 0)
                return v * valueMap[make_pair(source, str)];
        }
        return 0.0;
    }
};

可惡的是,想到這個思路了,寫的時候還反覆出現各類錯誤,讓人頭大。可能圖的問題我仍是不熟吧,還得多練練svg

相關文章
相關標籤/搜索