问题来源:https://leetcode.com/problems/pascals-triangle-ii/
import java.util.ArrayList;
import java.util.List;
/**
*
* <p>
* ClassName PascalIsTriangleII
* </p>
* <p>
* Description 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?
* </p>
*
* @author TKPad wangx89@126.com
* <p>
* Date 2015年3月27日 下午2:15:35
* </p>
* @version V1.0.0
*
*/
public class PascalIsTriangleII {
public List<Integer> getRow(int rowIndex) {
return generate(rowIndex + 1);
}
public List<Integer> generate(int numRows) {
if (numRows <= 0) {
return new ArrayList<Integer>();
}
List<Integer> temp = new ArrayList<Integer>();// 使用temp作为一个迭代器,来不断产生新的List
temp.add(1);
for (int i = 1; i < numRows; i++) {
List<Integer> generateList = generateList(temp);
temp = generateList;
}
return temp;
}
public List<Integer> generateList(List<Integer> temp) {
int first = temp.get(0);
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(first);
for (int i = 1; i < temp.size(); i++) {
al.add(first + temp.get(i));
first = temp.get(i);
}
al.add(temp.get(0));
return al;
}
public static void main(String[] args) {
List<Integer> row = new PascalIsTriangleII().getRow(0);
System.out.println(row);
}
}