15.杨辉三角II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_15014327/article/details/83662285

给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 行。

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 3
输出: [1,3,3,1]

代码:

public static List<Integer> getRow(int rowIndex) {
	List<List<Integer>> list = new ArrayList<List<Integer>>();
	if (rowIndex < 0) {
		return new ArrayList<Integer>();
	} else if (rowIndex == 0) {
		List<Integer> li = new ArrayList<Integer>();
		li.add(1);
		return li;
	}

	for (int i = 1; i <= rowIndex + 1; i++) {
		List li = new ArrayList();
		if (i == 1) {
			li.add(1);
			list.add(li);
			continue;
		}
		for (int j = 1; j <= i; j++) {
			if (j == 1) {
				li.add(1);
			} else {
				List<Integer> last = list.get(i - 2);
				int a = last.get(j - 2);
				int b = last.size() >= j ? last.get(j - 1) : 0;
				li.add(a + b);
			}
		}
		list.add(li);
	}
	return list.get(list.size() - 1);
}

猜你喜欢

转载自blog.csdn.net/qq_15014327/article/details/83662285