汇总下leetcode的twosum 和 path sum
为什么做过的还是不清楚呢 对不起我拉低 了人类的智商(哭)
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
直接DFS判断。 如果到了叶子结点 val == target, 说明存在;深度优先搜索左右子树,此时的target是减去根节点的值
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root == None:
return False
if root.val == sum and root.left == None and root.right == None:
return True
return self.find(root.left, sum-root.val) or self.find(root.right, sum-root.val)
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
这个是要列出所有的路径
一般要列出来的大多采用DFS+回溯, 通过一个函数递归实现。参数res存储所有的结果,path 存储每一条路径,每次递归完一次回溯到上一个结点,实现方法就是path pop掉最后一个结点。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
res = []
self.find(root, sum, res, [])
return res
def find(self, root, sum, res, path):
if root == None:
return
path.append(root.val)
if root.val == sum and root.left == None and root.right == None:
res.append(path[:])
if root.left:
self.find(root.left, sum-root.val, res, path)
if root.right:
self.find(root.right, sum-root.val, res, path)
path.pop()
you are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths that sum to 8 are:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
可以从任意一个结点开始向下走,只要可以相加得到sum就可以
所以递归调用,先从root开始,然后从left开始, 从right开始, 三者相加。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if root == None:
return 0
res = self.find(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum)
return res
def find(self, root, sum):
if root == None:
return 0
if root.val == sum:
res = 1
else:
res = 0
return res + self.find(root.left, sum-root.val)+ self.find(root.right, sum-root.val)
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for i, v in enumerate(nums):
if target - v not in dic:
dic[v] = i
else:
return [i, dic[target-v]]
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
class Solution(object):
def twoSum(self, nums, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
if nums == []:
return []
left = 0
right = len(nums)-1
while left < right:
if nums[left] + nums[right] == target:
return [left+1, right+1]
elif nums[left] + nums[right] < target:
left += 1
else:
right -= 1
Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True
Example 2:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: False
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findTarget(self, root, target):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
dic = {}
return self.find(root, target, dic)
def find(self, root, target,dic):
if root == None:
return False
if target-root.val not in dic:
dic[root.val] = 1
else:
return True
return self.find(root.left, target, dic) or self.find(root.right, target, dic)
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
首先数组排序。
排序之后选择一个数字,在剩下的数字中相当于twosum
但是要注意重复数字问题,选择第一个数字时,要排除重复一次。
双指针twosum时,也要排除重复。
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if nums == []:
return []
nums = sorted(nums)
res = []
for i in range(len(nums)):
if nums[i] > 0:
break
if i >0 and nums[i] == nums[i-1]:
continue
left = i+1
right = len(nums)-1
target = -nums[i]
while left < right:
if nums[left] + nums[right] == target:
res.append([nums[i], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]:
left += 1
while right > left and nums[right] == nums[right-1]:
right -= 1
left += 1
right -= 1
elif nums[left] + nums[right] < target:
left += 1
else:
right -= 1
return res
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
类似于threesum,数组排序是第一步。
然后取第一个数, 不能大于target/4
之后取第二个数,不能大于(target-nums[i]) / 3
之后就是双指针 进行twosum
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
if nums == []:
return []
res = []
nums = sorted(nums)
for i in range(len(nums)):
if nums[i] > target/ 4:
break
if i > 0 and nums[i] == nums[i-1]:
continue
for j in range(i+1, len(nums)):
if nums[j] > (target-nums[i]) / 3 :
break
if j >i+1 and nums[j] == nums[j-1]:
continue
left = j + 1
right = len(nums)-1
while left < right:
if nums[left] + nums[right] == target-nums[i]-nums[j]:
res.append([nums[i], nums[j], nums[left], nums[right]])
while left < right and nums[left] == nums[left+1]:
left += 1
while left < right and nums[right] == nums[right-1]:
right -=1
left += 1
right -= 1
elif nums[left] + nums[right] < target-nums[i]-nums[j]:
left += 1
else:
right -= 1
return res