【leetcode】【119】Pascal's Triangle II

一、问题描述

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(k),无非就是在原list上直接操作前面的值而已。直接上代码。

三、Java AC代码

public List<Integer> getRow(int rowIndex) {
        List<Integer> res = new ArrayList<Integer>();
		if (rowIndex < 0) {
			return res;
		}
		for (int i = 0; i <= rowIndex; i++) {
			res.add(1);
			int pre = 1;
			for (int j = 1; j < i; j++) {
				int cur = res.get(j);
				res.set(j, cur + pre);
				pre = cur;
			}
		}
		return res;
    }


你可能感兴趣的:(java,LeetCode,list)