力扣刷题日记【2022/1/31】
39. 组合总和
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
代码思路:
经典dfs,做好剪枝就行。
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res,n=[],len(candidates)
def fun(l,k):
if sum(l)==target:res.append(l)
if sum(l)>=target:return
for i in range(k,n):
fun(l+[candidates[i]],i)
return
fun([],0)
return res
114. 二叉树展开为链表
给你二叉树的根结点 root ,请你将它展开为一个单链表:
展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
展开后的单链表应该与二叉树 先序遍历 顺序相同。
代码思路:
这个题思考起来很简单,就是前序遍历一遍,然后建一个链表,但这个题坑的一点就是需要用旧的地址,所以得保存旧的节点,然后再旧的节点上更改
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
l=[]
def dfs(tree):
if tree:
l.append(tree)
dfs(tree.left)
dfs(tree.right)
dfs(root)
for i in range(1,len(l)):
pre,cur=l[i-1],l[i]
pre.right=cur
pre.left=None