您的位置:首页 > 其它

LeetCode 119. Pascal's Triangle II

2017-10-11 19:18 337 查看

问题描述

Given an index k, return the kth row of the Pascal’s triangle.

For example, given k = 3,

Return [1,3,3,1].

Note:

Could you optimize your algorithm to use only O(k) extra space?

题目描述

给定一个数,返回杨辉三角中对应的行。只能用O(n)的复杂度。这个题目使用一行数据,从最后一位开始计算杨辉三角的值。

算法实现

public List<Integer> getRow(int rowIndex) {
int num = rowIndex + 1;
int[] row = new int[num];
for (int i = 0; i < num; i++) {
row[0] = 1;
row[i] = 1;
for (int j = i - 1; j >= 1; j--) {
row[j] = row[j] + row[j - 1];
}
}
List<Integer> result = new ArrayList<Integer>();
for (int n : row) {
result.add(n);
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: