119. Pascal's Triangle II
Given an integer rowIndex
, return the rowIndexth
(0-indexed) row of the Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown.
Solution:
def getRow(rowIndex):
form = [1] * (rowIndex + 1)
for i in range(2, rowIndex+1):
for j in range(1, i):
form[i-j] += form[i-j-1]
return form
Remark:
Start from: rowIndex = 5
Process:
i | j | form
2 | 1 | [1, 2, 1, 1, 1, 1]
3 | 1 | [1, 2, 3, 1, 1, 1]
3 | 2 | [1, 3, 3, 1, 1, 1]
4 | 1 | [1, 3, 3, 4, 1, 1]
4 | 2 | [1, 3, 6, 4, 1, 1]
4 | 3 | [1, 4, 6, 4, 1, 1]
5 | 1 | [1, 4, 6, 4, 5, 1]
5 | 2 | [1, 4, 6, 10, 5, 1]
5 | 3 | [1, 4, 10, 10, 5, 1]
5 | 4 | [1, 5, 10, 10, 5, 1]
Result:
[1, 5, 10, 10, 5, 1]
Feedback:
Runtime: 45 ms, faster than 45.56% of Python3 online submissions for Pascal's Triangle II.
Memory Usage: 13.8 MB, less than 87.08% of Python3 online submissions for Pascal's Triangle II.
48. Rotate Image
You are given an n x n
2D matrix
representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Solution 1:
class Solution:
def rotate(self, matrix):
l = len(matrix)
matrix_copy = list(matrix)
for i in range(l):
matrix[i] = []
for j in range(l):
matrix[i].append(matrix_copy[l-j-1][i])
Remark:
Eg: Input: [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
Read the Output: (t: matrix)
- element 0: t[3][0], t[2][0], t[1][0], t[0][0]
- element 1: t[3][1], t[2][1], t[1][1], t[0][1]
- element 2: t[3][2], t[2][2], t[1][2], t[0][2]
- element 3: t[3][3], t[2][3], t[1][3], t[0][3]
There are two sequences from element 0 to element 3: [0, 1, 2, 3] and [3, 2, 1, 0]
Use for loop (i) to denote the sequence [0, 1, 2, 3];
In each loop (i), we use for loop (j) to denote the sequence [3, 2, 1, 0].
Feedback:
Runtime: 36 ms, faster than 85.90% of Python3 online submissions for Rotate Image.
Memory Usage: 13.9 MB, less than 71.51% of Python3 online submissions for Rotate Image.
Solution 2:
class Solution:
def rotate(self, matrix):
matrix[:] = zip(*matrix[::-1])
Feedback:
Runtime: 32 ms, faster than 94.61% of Python3 online submissions for Rotate Image.
Memory Usage: 13.9 MB, less than 91.28% of Python3 online submissions for Rotate Image.
To be continued... : )