LeetCode 118：杨辉三角 II Pascal's Triangle II

0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## LeetCode 118：杨辉三角 II Pascal's Triangle II

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.

In Pascal's triangle, each number is the sum of the two numbers directly above it.

输入: 3

### 解题思路：

[1]

[1,1]

[1,2,1] 索引1 的值是索引 0 和 1的和，没问题

[1,3,4,1] 索引2 的值是索引 2 和索引 1的和 为4，而不是预期的3

class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> nums = new ArrayList<Integer>();
for (int i = 1; i <= rowIndex; i++) {
for (int j = i - 1; j > 0; j--) {
nums.set(j, nums.get(j) + nums.get(j - 1));
}
System.out.println(nums);
}
return nums;
}
}

### Java：

class Solution {
public List<Integer> getRow(int rowIndex) {
Integer[] nums = new Integer[rowIndex+1];//所有值被默认置为0
Arrays.fill(nums, 0);
nums[0] = 1;
for (int i = 1; i <= rowIndex; i++) {
for (int j = i; j >0; j--) {
nums[j] = nums[j] + nums[j-1];//当j为1时，nums[j]为0，不影响最后一个值，不用单独给每行末尾赋值1
}
}
return Arrays.asList(nums);//转为List<Integer>型并返回
}
}

### Python3：

class Solution:
def getRow(self, rowIndex: int) -> List[int]:
nums = [1]
for i in range(1, rowIndex+1):
for j in range(i-1, 0, -1):
nums[j] +=nums[j-1]
nums.append(1) # 需要给末尾索引赋值1
return nums

+ 关注