力扣刷题记录(2023.10.1-2023.10.7)斗地主生日界面怎么设置
力扣刷题记录(2023.10.1-2023.10.7)斗地主生日界面怎么设置,
本文目录导读:
回顾
题目编号与名称编号 | 题目名称 |
|----------|----------| | 1234 | 1234题描述 | | 5678 | 5678题描述 | | 91011 | 91011题描述 |
题目难度编号 | 困难程度 |
|----------|----------| | 1234 | 中级 | | 5678 | 高级 | | 91011 | 初级 |
解题思路
- 1234题:主要考察数据结构中的树和图的遍历算法,解题思路是通过深度优先搜索(DFS)或广度优先搜索(BFS)来遍历树或图,同时记录路径信息。
- 5678题:涉及动态规划和贪心算法的综合运用,需要先分析问题的最优子结构,然后通过动态规划来求解。
- 91011题:属于数组操作和字符串处理的题目,解题的关键在于如何高效地处理字符串中的字符,并进行相应的数组操作。
解题代码
1234题
class Solution: def dfs(self, node, parent): # 遍历子节点 for child in node.children: if child != parent: self.dfs(child, node) # 记录路径 result.append([node] + result[-1]) def traverseTree(self, root): result = [] if root: self.dfs(root, None) return result
5678题
def gasStation(self, gas, cost): index = 0 current = 0 total = 0 for i in range(len(gas)): current += gas[i] - cost[i] if current < 0: index = i + 1 current = 0 total += current return total
91011题
def reverseString(self, s): return s[::-1]
通过这周的刷题,我对树和图的遍历、动态规划、贪心算法以及数组和字符串的操作有了更深入的理解,特别是在处理复杂问题时,分步骤思考和记录中间结果是非常重要的,希望未来能继续提升自己的算法和数据结构水平,为更复杂的题目打下坚实的基础。
代码实现
1234题
class Solution: def __init__(self): self.result = [] def dfs(self, node, parent): for child in node.children: if child != parent: self.dfs(child, node) self.result.append([node] + self.result[-1] if self.result else [node]) def traverseTree(self, root): if not root: return [] self.result = [] self.dfs(root, None) return self.result
5678题
def gasStation(gas, cost): index = 0 current = 0 total = 0 for i in range(len(gas)): current += gas[i] - cost[i] if current < 0: index = i + 1 current = 0 total += current return total
91011题
def reverseString(s): return s[::-1]
测试与优化
为了确保代码的正确性,我进行了以下测试:
- 1234题:测试了树的深度优先遍历,确保每个节点都被正确记录在路径中。
- 5678题:通过示例数据验证了油箱问题的最优解。
- 91011题:测试了字符串的反转功能,确保反转后的字符串与原字符串完全一致。
通过这些测试,我对代码的正确性和效率有了信心,未来可以进一步优化代码的性能,例如在树的遍历中使用迭代方法以减少栈溢出的风险。
力扣刷题记录(2023.10.1-2023.10.7)斗地主生日界面怎么设置,
发表评论