擅长:python、mysql、java
<p>如果你从右到左重新考虑这个问题,而不是从左到右,它会简化很多:</p>
<pre><code>rows = int(input("Enter the desired height: "))
array = []
for row in range(1, rows + 1):
array.append(1) # both widen the row and initialize last element
for i in range(row - 2, 0, -1): # fill in the row, right to left
array[i] += array[i - 1] # current computed from previous
print("Row", row, array)
</code></pre>
<p><strong>输出</strong></p>
<pre><code>Enter the desired height: 9
Row 1 [1]
Row 2 [1, 1]
Row 3 [1, 2, 1]
Row 4 [1, 3, 3, 1]
Row 5 [1, 4, 6, 4, 1]
Row 6 [1, 5, 10, 10, 5, 1]
Row 7 [1, 6, 15, 20, 15, 6, 1]
Row 8 [1, 7, 21, 35, 35, 21, 7, 1]
Row 9 [1, 8, 28, 56, 70, 56, 28, 8, 1]
</code></pre>