Skip to content

Instantly share code, notes, and snippets.

View liyunrui's full-sized avatar

Ray liyunrui

  • Singapore
View GitHub Profile
@liyunrui
liyunrui / 494. Target Sum.py
Created February 27, 2021 14:49
leetcode-dp
class Solution:
"""
To clarify:
what's range of S?
what's range of nums? sum(nums) <= 1000 and len(nums) <= 20
"""
def findTargetSumWays(self, nums: List[int], S: int) -> int:
"""
Brute Force
T:O(2^n)
# 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:
"""
Problem Clarification:
Can I assume value of node in the tree is unique? No
# 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:
"""
This code reuses the recursive function from Lowest Common Ancestor of Binary Tree (#236)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
"""
For each given current node, we need to determine where to search the common ancestor.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
"""
For each current given root node, we try to find if given nodes in the left subtree and give nodes in the right subtree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
"""
For each current given root node, we try to find p in the left subtree and q in the right subtree.
class Solution:
"""
Greedy+stack:
We use stack to keep track of index of unmatched parentheses.
Top of stack is nearest index of unmatched parenthese.
We traverse the given string forward.
Initally, we put -1 in the stack.
如果又括號就進stack, 左括號就出stack, 然後計算長度
when encounter the open parenthese, we append the index
class Solution:
"""
Greedy+stack:
We use stack to keep track of index of unmatched left parentheses.
Top of stack is nearest index of unmatched left parenthese.
We traverse the given string forward.
when encounter the open parenthese, we append the index
when encounter the close parenthese,
if stack is empty, we need to remove current close parenthese to get valid paretheses
class Solution:
"""
Thought Process
Brute Force:
Two pointers:
T: O(n^2)
S: O(1)
Stack:
we use stack to maintain the minimum height on the left side of heights[i].
And, the top of stack is closest index of minimum height.
class Solution:
"""
1.Hashmap used to detected repeated number
2.Two pointers to reduce space complexity.
using slow/fater pointer
1. Intialize slow and fast pointer
-slow:s = n
-fast:f = self.get_square_sum(n)
2.when slow!=fast:
keep runing till we meet the cycle(s==f)