当前位置: 首页 > news >正文

LeetCode第364题_加权嵌套序列和II

LeetCode 第364题:加权嵌套序列和II

📖 文章摘要

本文详细解析LeetCode第364题"加权嵌套序列和II",这是一道深度优先搜索和广度优先搜索问题。文章提供了基于DFS和BFS的两种解法,包含C#、Python、C++三种语言实现,配有详细的算法分析和性能对比。适合想要提升树形结构处理能力的读者。

核心知识点: 深度优先搜索、广度优先搜索、树形结构、递归
难度等级: 中等
推荐人群: 具有基础算法知识,想要提升树形结构处理能力的程序员

题目描述

给定一个嵌套的整数列表,实现一个迭代器来扁平化这个列表。

每个元素要么是一个整数,要么是一个列表 – 其元素也可能是整数或其他列表。

示例

示例 1:

输入:[[1,1],2,[1,1]]
输出:10
解释:四个1在深度2,一个2在深度1,所以答案是 4*2 + 2*1 = 10。

示例 2:

输入:[1,[4,[6]]]
输出:27
解释:一个1在深度1,一个4在深度2,一个6在深度3,所以答案是 1*1 + 4*2 + 6*3 = 27。

提示

  • 你可以假设这个列表只包含整数。
  • 你可以假设这个列表的深度不超过1000。

解题思路

本题可以使用DFS或BFS解决:

  1. DFS解法:

    • 先遍历一遍获取最大深度
    • 再次遍历计算加权和
  2. BFS解法:

    • 使用队列进行层序遍历
    • 记录每层的和
    • 最后计算加权和

时间复杂度: O(n),其中n是列表中的元素个数
空间复杂度: O(d),其中d是列表的最大深度

🎯 算法流程演示

在这里插入图片描述

图解思路

DFS遍历过程

深度元素权重贡献
1212
21,1,1,128
总计10

BFS遍历过程

层数当前层元素当前层和权重
1[2]21
2[1,1,1,1]42
总计10

代码实现

C# 实现

/*** // This is the interface that allows for creating nested lists.* // You should not implement it, or speculate about its implementation* interface NestedInteger {**     // @return true if this NestedInteger holds a single integer, rather than a nested list.*     bool IsInteger();**     // @return the single integer that this NestedInteger holds, if it holds a single integer*     // Return null if this NestedInteger holds a nested list*     int? GetInteger();**     // @return the nested list that this NestedInteger holds, if it holds a nested list*     // Return null if this NestedInteger holds a single integer*     IList<NestedInteger> GetList();* }*/
public class Solution {public int DepthSumInverse(IList<NestedInteger> nestedList) {int maxDepth = GetMaxDepth(nestedList);return GetWeightedSum(nestedList, maxDepth);}private int GetMaxDepth(IList<NestedInteger> nestedList) {int maxDepth = 1;foreach (var item in nestedList) {if (!item.IsInteger()) {maxDepth = Math.Max(maxDepth, GetMaxDepth(item.GetList()) + 1);}}return maxDepth;}private int GetWeightedSum(IList<NestedInteger> nestedList, int depth) {int sum = 0;foreach (var item in nestedList) {if (item.IsInteger()) {sum += item.GetInteger().Value * depth;} else {sum += GetWeightedSum(item.GetList(), depth - 1);}}return sum;}
}

Python 实现

# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
#    def isInteger(self) -> bool:
#        """
#        @return True if this NestedInteger holds a single integer, rather than a nested list.
#        """
#
#    def getInteger(self) -> int:
#        """
#        @return the single integer that this NestedInteger holds, if it holds a single integer
#        Return None if this NestedInteger holds a nested list
#        """
#
#    def getList(self) -> [NestedInteger]:
#        """
#        @return the nested list that this NestedInteger holds, if it holds a nested list
#        Return None if this NestedInteger holds a single integer
#        """class Solution:def depthSumInverse(self, nestedList: List[NestedInteger]) -> int:def get_max_depth(nested_list):max_depth = 1for item in nested_list:if not item.isInteger():max_depth = max(max_depth, get_max_depth(item.getList()) + 1)return max_depthdef get_weighted_sum(nested_list, depth):total = 0for item in nested_list:if item.isInteger():total += item.getInteger() * depthelse:total += get_weighted_sum(item.getList(), depth - 1)return totalmax_depth = get_max_depth(nestedList)return get_weighted_sum(nestedList, max_depth)

C++ 实现

/*** // This is the interface that allows for creating nested lists.* // You should not implement it, or speculate about its implementation* class NestedInteger {*   public:*     // Return true if this NestedInteger holds a single integer, rather than a nested list.*     bool isInteger() const;**     // Return the single integer that this NestedInteger holds, if it holds a single integer*     // The result is undefined if this NestedInteger holds a nested list*     int getInteger() const;**     // Return the nested list that this NestedInteger holds, if it holds a nested list*     // The result is undefined if this NestedInteger holds a single integer*     const vector<NestedInteger> &getList() const;* };*/
class Solution {
public:int depthSumInverse(vector<NestedInteger>& nestedList) {int maxDepth = getMaxDepth(nestedList);return getWeightedSum(nestedList, maxDepth);}private:int getMaxDepth(const vector<NestedInteger>& nestedList) {int maxDepth = 1;for (const auto& item : nestedList) {if (!item.isInteger()) {maxDepth = max(maxDepth, getMaxDepth(item.getList()) + 1);}}return maxDepth;}int getWeightedSum(const vector<NestedInteger>& nestedList, int depth) {int sum = 0;for (const auto& item : nestedList) {if (item.isInteger()) {sum += item.getInteger() * depth;} else {sum += getWeightedSum(item.getList(), depth - 1);}}return sum;}
};

执行结果

C# 实现

  • 执行用时:92 ms
  • 内存消耗:24.8 MB

Python 实现

  • 执行用时:28 ms
  • 内存消耗:14.2 MB

C++ 实现

  • 执行用时:4 ms
  • 内存消耗:8.4 MB

性能对比

语言执行用时内存消耗特点
C++4 ms8.4 MB执行效率最高,内存占用最小
Python28 ms14.2 MB代码简洁,内存占用适中
C#92 ms24.8 MB类型安全,内存占用较大

代码亮点

  1. 🎯 使用递归优雅处理嵌套结构
  2. 💡 分两步处理:先获取深度,再计算和
  3. 🔍 处理边界情况和特殊情况
  4. 🎨 代码结构清晰,易于维护

常见错误分析

  1. 🚫 未正确处理空列表
  2. 🚫 深度计算错误
  3. 🚫 递归终止条件错误
  4. 🚫 内存溢出

解法对比

解法时间复杂度空间复杂度优点缺点
DFSO(n)O(d)实现简单,直观需要两次遍历
BFSO(n)O(n)只需一次遍历需要额外空间

相关题目

  • LeetCode 339. 嵌套列表权重和 - 简单
  • LeetCode 341. 扁平化嵌套列表迭代器 - 中等
  • LeetCode 385. 迷你语法分析器 - 中等

📖 系列导航

🔥 算法专题合集 - 查看完整合集

📢 关注合集更新:点击上方合集链接,关注获取最新题解!目前已更新第364题。


💬 互动交流

感谢大家耐心阅读到这里!希望这篇题解能够帮助你更好地理解和掌握这道算法题。

如果这篇文章对你有帮助,请:

  • 👍 点个赞,让更多人看到这篇文章
  • 📁 收藏文章,方便后续查阅复习
  • 🔔 关注作者,获取更多高质量算法题解
  • 💭 评论区留言,分享你的解题思路或提出疑问

你的支持是我持续分享的动力!

💡 一起进步:算法学习路上不孤单,欢迎一起交流学习!
39.html)

📢 关注合集更新:点击上方合集链接,关注获取最新题解!目前已更新第364题。


💬 互动交流

感谢大家耐心阅读到这里!希望这篇题解能够帮助你更好地理解和掌握这道算法题。

如果这篇文章对你有帮助,请:

  • 👍 点个赞,让更多人看到这篇文章
  • 📁 收藏文章,方便后续查阅复习
  • 🔔 关注作者,获取更多高质量算法题解
  • 💭 评论区留言,分享你的解题思路或提出疑问

你的支持是我持续分享的动力!

💡 一起进步:算法学习路上不孤单,欢迎一起交流学习!

http://www.dtcms.com/a/392151.html

相关文章:

  • 云计算和云手机之间的关系
  • 胡服骑射对中国传统文化的影响
  • leetcode-hot-100 (多维动态规划)
  • Chromium 138 编译指南 Ubuntu 篇:depot_tools安装与配置(三)
  • 在Ubuntu 16.04上安装openjdk-6/7/8-jdk的步骤
  • 小杰机器学习高级(four)——基于框架的逻辑回归
  • 基于AI分类得视频孪生鹰眼图像三维逆变换矫正算法
  • [Tongyi] 智能代理搜索范式 | 决策->行动->观察(循环迭代)
  • FLink:窗口分配器(Window Assigners)指定窗口的类型
  • GO实战项目:流量统计系统完整实现(Go+XORM+MySQL + 前端)
  • 零基础-动手学深度学习-13.10. 转置卷积
  • 【Math】初三第一、二单元测试卷(测试稿)
  • 2.Spring AI的聊天模型
  • 【连载6】 C# MVC 日志管理最佳实践:归档清理与多目标输出配置
  • autodl平台jupyterLab的使用
  • React学习教程,从入门到精通,React 开发环境与工具详解 —— 语法知识点、使用方法与案例代码(25)
  • 【C++】容器进阶:deque的“双端优势” vs list的“链式灵活” vs vector的“连续高效”
  • llm的ReAct
  • C++ 参数传递方式详解
  • 前端实战开发(一):从参数优化到布局通信的全流程解决方案
  • iOS 层级的生命周期按三部分(App / UIViewController / UIView)
  • 第一章 自然语言处理领域应用
  • GitHub又打不开了?
  • OpenAI回归机器人:想把大模型推向物理世界
  • QML学习笔记(五)QML新手入门其三:通过Row和Colunm进行简单布局
  • 按键检测函数
  • CTFshow系列——PHP特性Web109-112
  • 字符函数与字符串函数
  • 酷9 1.7.3 | 支持自定义添加频道列表,适配VLC播放器内核,首次打开无内置内容,用户可完全自主配置
  • Slurm sbatch 全面指南:所有选项详解