Cho số n, tìm hàng thứ n (0-indexed) của tam giác Pascal.
Ví dụ
Đầu vào: 4.
Đầu ra: [1, 4, 6, 4, 1].
Thuật toán
- Nếu
n==0trả về[1]; nếun==1trả về[1,1]. - Khởi tạo
ls = [1,1],temp = [1,1]. - Với
itừ 2 đếnn:ls = temp,temp = [1].- Với
jtừ 0 đếnlen(ls)-2:temp.append(ls[j]+ls[j+1]). temp.append(1).
- Trả về
temp.
Mã nguồn Python
class Solution:
def solve(self, n):
if n == 0:
return [1]
if n == 1:
return [1,1]
ls = [1,1]
temp = [1,1]
for i in range(2, n+1):
ls = temp
temp = [1]
for j in range(len(ls)-1):
temp.append(ls[j] + ls[j+1])
temp.append(1)
return temp
ob = Solution()
print(ob.solve(4))
Đầu vào / Đầu ra
Input: 4
Output: [1, 4, 6, 4, 1]