Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
path-sum-iv.cpp 1.08 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2017-08-30 09:41 +08:00 . Update path-sum-iv.cpp
// Time: O(n)
// Space: O(p), p is the number of paths
class Solution {
public:
int pathSum(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
int result = 0;
queue<node> q;
node dummy(10);
auto parent_ptr = &dummy;
for (const auto& num : nums) {
node child(num);
while (!parent_ptr->isParent(child)) {
result += parent_ptr->leaf ? parent_ptr->val : 0;
parent_ptr = &q.front();
q.pop();
}
parent_ptr->leaf = false;
child.val += parent_ptr->val;
q.emplace(move(child));
}
while (!q.empty()) {
result += q.front().val;
q.pop();
}
return result;
}
private:
struct node {
int level, i, val;
bool leaf;
node(int n) : level(n / 100 - 1), i((n % 100) / 10 - 1), val(n % 10), leaf(true) {};
inline bool isParent(const node& other) {
return level == other.level - 1 && i == other.i / 2;
};
};
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助