Commit e1017a70 authored by jiang feng's avatar jiang feng
Browse files

Update 22.py, 24.py, 06.py, 23.py, 26.py, 32.py, 25.py, 11.py, 8.py, 19.py,...

Update 22.py, 24.py, 06.py, 23.py, 26.py, 32.py, 25.py, 11.py, 8.py, 19.py, 18.py, 17.py, 16.py, 15.py, 14.py, 4.py, 46.py, 48.py, 53.py, 45.py, 44.py, 42.py, 60.py, 05.py, 03.py, 41.py, 36.py, 65.py, 34.py, 33.py, 31.py, 70.py, 56.py, 54.py, 73.py, 40.py, 78.py, 30.py, 72.py, 66.py, 64.py, 63.py, 74.py, 81.py, 86.py, 85.py, 83.py, 87.py, 79.py, 93.py, 92.py, 82.py, 94.py, 62.py, TwoSum.py, 90.py, 80.py, 91.py, 67.py, 39.py, 38.py, 71.py, 95.py, 10.py, 75.py, 61.py, 57.py, 97.py, 99.py, 98.py files
parents
'''
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
'''
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = [[]]
for num in nums:
for index in range(len(result)):
new_list = result[index] + [num]
new_list.sort()
result.append(new_list)
unique = set(tuple(val) for val in result)
return list(list(val) for val in unique)
\ No newline at end of file
'''
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
'''
class Solution(object):
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
if not s or s[0] == '0':
return 0
if len(s) == 1:
return 1
dp = [0]*len(s)
dp[0] = 1
if int(s[:2]) > 26:
if s[1] != '0':
dp[1] = 1
else:
dp[0] = 0
else:
if s[1] != '0':
dp[1] = 2
else:
dp[1] = 1
for index in range(2, len(s)):
if s[index] != '0':
dp[index] += dp[index-1]
val = int(s[index-1:index+1])
if val >= 10 and val <= 26:
dp[index] += dp[index-2]
return dp[len(s)-1]
# Time: O(N)
# Space: O(N)
\ No newline at end of file
'''
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if m == n :
return head
result = ListNode(0)
result.next = head
prev = result
for index in range(m-1):
prev = prev.next
reverse = None
curr = prev.next
for i in range(n-m+1):
temp = curr.next
curr.next = reverse
reverse = curr
curr = temp
prev.next.next = curr
prev.next = reverse
return result.next
\ No newline at end of file
'''
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
'''
class Solution(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
result = []
def dfs(s, temp, count):
if count == 4:
if not s:
result.append(temp[:-1])
return
for index in range(1, 4):
if index <= len(s):
if index == 1:
dfs(s[index:], temp + s[:index] + ".", count+1)
elif index ==2 and s[0] != '0':
dfs(s[index:], temp + s[:index] + ".", count+1)
elif index == 3 and s[0] != '0' and int(s[:3]) <= 255:
dfs(s[index:], temp + s[:index] + ".", count+1)
dfs(s, "", 0)
return result
\ No newline at end of file
'''
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
'''
# 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 inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
stack, result = [root], []
while stack:
if root.left:
stack.append(root.left)
root = root.left
else:
node = stack.pop()
result.append(node.val)
if node.right:
stack.append(node.right)
root = node.right
return result
\ No newline at end of file
'''
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Example:
Input: 3
Output:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
'''
# 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 generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n == 0:
return []
def generate(start, end):
result = []
if start > end:
result.append(None)
return result
for index in range(start, end+1):
left = generate(start, index-1)
right = generate(index+1, end)
for l in left:
for r in right:
current = TreeNode(index)
current.left = l
current.right = r
result.append(current)
return result
return generate(1, n)
\ No newline at end of file
'''
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
Example 1:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true
Example 2:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false
'''
class Solution(object):
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
if len(s3) != len(s1) + len(s2):
return False
dp = [[False for _ in range(len(s2)+1)] for _ in range(len(s1)+1)]
for row in range(len(s1)+1):
for col in range(len(s2)+1):
if row == 0 and col == 0:
dp[row][col] = True
elif row == 0:
dp[row][col] =dp[row][col-1] and s2[col-1] == s3[row+col-1]
elif col == 0:
dp[row][col] = dp[row-1][col] and s1[row-1] == s3[row+col-1]
else:
dp[row][col] = (dp[row][col-1] and s2[col-1] == s3[row+col-1]) or (dp[row-1][col] and s1[row-1] == s3[row+col-1])
return dp[len(s1)][len(s2)]
# Time: O(m*n)
# Space: O(m*n)
\ No newline at end of file
'''
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
'''
# 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 isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
stack, result = [], []
while stack or root:
if root:
stack.append(root)
root = root.left
else:
root = stack.pop()
result.append(root.val)
root = root.right
previous = result[0]
for index in range(1, len(result)):
if previous >= result[index]:
return False
previous = result[index]
return True
'''
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
Input: [1,3,null,null,2]
1
/
3
\
2
Output: [3,1,null,null,2]
3
/
1
\
2
'''
# 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 recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
first, second, prev = None, None, None
def inorder(root):
if root:
inorder(root.left)
if prev is not None and root.val < prev.val:
if first is None:
first = root
else:
second = root
prev = root
inorder(root.right)
inorder(root)
if first and second:
first.val, second.val = second.val, first.val
\ No newline at end of file
'''
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):
mapping = {}
for index, val in enumerate(nums):
diff = target - val
if diff in mapping:
return [index, mapping[diff]]
else:
mapping[val] = index
# Space: O(N)
# Time: O(N)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment