leetcode_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].

思路:

就是类似杨辉三角的问题,用两个数组存储相邻的两行然后用第一行来算第二行即可,将计算到第k行的数据存储到list中即可。

代码:

public List getRow(int rowIndex) {
		List subList = new ArrayList();
		int numRows = rowIndex + 1;
		if (numRows <= 0)
			return subList;
		int arr[][] = new int[numRows][];
		arr[0] = new int[1];
		Arrays.fill(arr[0], 1);
		if (numRows > 1) {
			arr[1] = new int[2];
			Arrays.fill(arr[1], 1);
		}
		for (int i = 2; i < numRows; i++) {
			arr[i] = new int[i + 1];
			arr[i][0] = 1;
			for (int j = 1; j < i; j++)
				arr[i][j] = arr[i - 1][j] + arr[i - 1][j - 1];// to caculate the
																// piscal
																// triganle
			arr[i][i] = 1;
		}

		for (int num : arr[rowIndex])
			subList.add(num);
		return subList;
	}


你可能感兴趣的:(leetcode,Java,leetcode题解)