编程-BFS
给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。
树的序列化输入是用层序遍历,每组子节点都由 null 值分隔(参见示例)。
示例 1:

输入:root = [1,null,3,2,4,null,5,6] 输出:[[1],[3,2,4],[5,6]]
示例 2:

输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] 输出:[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution { public: vector<vector<int>> levelOrder(Node* root) { if (!root) return {}; vector<vector<int>> result; deque<Node*> worker; worker.push_back(root); while (worker.size()) { vector<int> sub; int loops = worker.size(); while (loops--) { root = worker.front(), worker.pop_front(); for (auto &i : root->children) worker.push_back(i); sub.push_back(root->val); } result.push_back(sub); } return result; } };
https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/solution/cdfsbfsji-jian-dai-ma-miao-dong-by-fengz-g48b/
279. 完全平方数
给定正整数 n,找到若干个完全平方数(比如
1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。给你一个整数 n ,返回和为 n 的完全平方数的 最少数量 。
完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如,1、4、9 和 16 都是完全平方数,而 3 和 11 不是。
示例 1:
输入:n =12输出:3 解释:12 = 4 + 4 + 4
示例 2:
输入:n =13输出:2 解释:13 = 4 + 9
提示:
1 <= n <= 104
class Solution { public: int numSquares(int n) { unordered_set<int> visited; queue<int> Q; int step = 1; Q.push(n); while (Q.size()) { int cur_len = Q.size(); while (cur_len --) { int x = Q.front(); Q.pop(); for (int y = (int)sqrt(x); y > 0; y --) { int t = x - y * y; if (t == 0) return step; if (visited.find(t) == visited.end()) { visited.insert(t); Q.push(t); } } } step ++; } return 0; } };
https://leetcode-cn.com/problems/perfect-squares/solution/cpython3-1bfs-2bei-bao-wen-ti-by-hanxin_-sfk2/
https://zhuanlan.zhihu.com/p/136716105
https://leetcode-cn.com/problems/perfect-squares/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by--51/

浙公网安备 33010602011771号