关于LeetCode杨辉三角题解中map部分的技术疑问
map Hey there! Let's walk through this neat Pascal's Triangle solution step by step, focusing on the map part that's throwing you off—it's actually a really clever trick once you see how it works.
Let's start with the basics
First, the code initializes res = [[1]]—that's just the first row of Pascal's Triangle, which always starts with a single 1.
The loop: building each subsequent row
The loop runs from 1 to numRows-1 (since range(1, numRows) excludes the upper bound). For each iteration, we're generating the next row based on the last row we've already added to res.
The magic line with map
Let's break down this core line:
res += [map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1])]
Let's use concrete examples to make this click:
First iteration (generating the second row):
res[-1]is the last row in our result so far:[1]res[-1] + [0]becomes[1, 0](we add a 0 to the end of the last row)[0] + res[-1]becomes[0, 1](we add a 0 to the start of the last row)- Now
map(lambda x,y: x+y, ...)takes these two lists and adds their elements at each position:- 1 + 0 = 1
- 0 + 1 = 1
- This gives us the second row:
[1, 1]
Second iteration (generating the third row):
res[-1]is now[1, 1]res[-1] + [0]→[1, 1, 0][0] + res[-1]→[0, 1, 1]- Adding corresponding elements:
- 1 + 0 = 1
- 1 + 1 = 2
- 0 + 1 = 1
- That gives us the third row:
[1, 2, 1]
Why this works
Pascal's Triangle rule says each element (except the first and last of each row) is the sum of the element directly above it and the element above and to the left. By adding a 0 to both ends of the last row, we're essentially "padding" it so that every position in the new row can be calculated as the sum of two elements from the padded rows—this covers both the edge elements (which sum a 0 and the edge 1 from the last row) and the inner elements (which sum two adjacent elements from the last row).
A quick note: In Python 3, map() returns an iterator instead of a list, so you'd need to wrap it in list() to get a concrete list (like list(map(...))). The original code might be from Python 2, where map() returns a list directly.
The final return
return res[:numRows] handles edge cases where numRows is 0 (it returns an empty list) or if we initialized with more rows than needed (though in this code, we build exactly numRows rows, so it's mostly a safety measure).
内容的提问来源于stack exchange,提问作者Peter Tsung

