Rotate Image
48. Rotate Image
Solution
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for i in range(n/2):
for j in range(n-n/2):
matrix[i][j], matrix[~j][i], matrix[~i][~j], matrix[j][~i] = \
...
Group Anagrams
49. Group Anagrams
Solution 1
Get sorted chars array in each str.
Store the strs with the same chars array into the same dictionary item.
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
dic = {}
for s in strs:
chars = ''.join(sorted(s))
if chars i...
Subsets
78. Subsets
Solution 1
Each element can be contained or not contained.
Consider these two situations and continuously append the prefix to the result.
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
self.res = []
def generate(sub_nums, is_contained):
if len(sub...
Generate Parentheses
22. Generate Parentheses
Solution
As long as open > close in the sequence, the sequence is valid.
In this case we can either append ‘(‘ if we still have open quota, or append ‘)’ if we have more open than
close in the sequence.
When close is used up, we have generated all parentheses.
def generateParenthesis(...
Permutations
46. Permutations
Solution
dfs(nums = [1, 2, 3] , path = [] , result = [] )
|__ dfs(nums = [2, 3] , path = [1] , result = [] )
| |dfs(nums = [3] , path = [1, 2] , result = [] )
| | |dfs(nums = [] , path = [1, 2, 3] , result = [[1, 2, 3]] )
| |dfs(nums = [2] , path = [1, 3] , result = [[1, 2, 3]] )
| |dfs(nums = [] , pa...
Daily Temperatures
739. Daily Temperatures
Solution
When a warmer temperature comes in, pop all temperature before and lower than it.
def dailyTemperatures(self, T):
"""
:type T: List[int]
:rtype: List[int]
"""
stack = []
res = [0] * len(T)
for i, t in enumerate(T):
while stack and stack[-1][1] < t:
idx, prev...
Queue Reconstruction by Height
406. Queue Reconstruction by Height
Solution
Consider the shortest person, his k is the index he should be at.
For the other people, use the same idea. Keep None to represent ‘empty’.
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
people.sort()
empt...
Counting Bits
338. Counting Bits
Solution
Use the characteristic of odd and even numbers, i.e. odd number end with 1 and even number end with 0.
Can use num // 2 as memory.
Reference
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
bitCountList = [0]
for i in range(1, num + 1):
bitCount...
199 post articles, 25 pages.