`
dugu108
  • 浏览: 23229 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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?

import java.util.ArrayList;

public class Solution {
	public ArrayList<Integer> getRow(int rowIndex) {
		ArrayList<Integer> result = new ArrayList<Integer>();
		result.add(1);
		if (rowIndex == 0)
			return result;
		int[] odd = new int[rowIndex + 1];
		odd[0] = 1;
		int[] even = new int[rowIndex + 1];
		even[0] = 1;

		for (int i = 1; i <= rowIndex; i++) {
			if (i % 2 != 0) {
				int j = 1;
				for (; j <= i - 1; j++) {
					odd[j] = even[j] + even[j - 1];
				}
				odd[j] = 1;
			} else {
				int j = 1;
				for (; j <= i - 1; j++) {
					even[j] = odd[j] + odd[j - 1];
				}
				even[j] = 1;
			}
		}
		if (rowIndex % 2 != 0) {
			int index = 1;
			while (odd[index] != 1) {
				result.add(odd[index]);
				index++;
			}
		} else {
			int index = 1;
			while (even[index] != 1) {
				result.add(even[index]);
				index++;
			}
		}
		result.add(1);

		return result;
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics