classSolution { public: intpathSum(vector<int>& nums){ unordered_map<int, int> t; for (int x : nums) { t[x / 10] = x % 10; // 利用现有父子关系 } dfs(t, 11, 0); return res; }
voiddfs(unordered_map<int, int> &t, int i, int s){ if (!t.count(i)) return; s += t[i]; int r = i + 10 + i % 10, l = r - 1; // 33->45和46即33->43然后43+3得到46再-1得到45 if (!t.count(l) && !t.count(r)) { res += s; return; } dfs(t, l, s); dfs(t, r, s); }
voiddfs(unordered_map<int, int> &t, int i, int s){ if (!t.count(i)) return; s += t[i]; int l = i << 1, r = l + 1; if (!t.count(l) && !t.count(r)) { res += s; return; } dfs(t, l, s); dfs(t, r, s); }
classSolution { public: intpathSum(vector<int>& nums){ vector<int> t(32, -1); for (int x : nums) { t[(1 << (x / 100 - 1)) + x % 100 / 10 - 1] = x % 10; } dfs(t, 1, 0); return res; }
voiddfs(constvector<int> &t, int i, int s){ if (t[i] == -1) return; s += t[i]; int l = i << 1, r = l + 1; if (t[l] == -1 && t[r] == -1) { res += s; return; } dfs(t, l, s); dfs(t, r, s); }
voiddfs(constarray<int, 32> &t, int i, int s){ if (t[i] == -1) return; s += t[i]; int l = i << 1, r = l + 1; if (t[l] == -1 && t[r] == -1) { res += s; return; } dfs(t, l, s); dfs(t, r, s); }
classSolution { public: intpathSum(vector<int>& nums){ int t[32] = {0}; for (int x : nums) { t[(1 << (x / 100 - 1)) + x % 100 / 10 - 1] = x; } dfs(t, 1, 0); return res; }
voiddfs(int t[], int i, int s){ if (t[i] == 0) return; s += t[i] % 10; int l = i << 1, r = l + 1; if (t[l] == -1 && t[r] == -1) { res += s; return; } dfs(t, l, s); dfs(t, r, s); }