标签:blog io ar java for 2014 on log ad
题目:给定一个行数n,生成n行帕斯卡三角形
算法:逐层遍历数组
public class Solution { public List<List<Integer>> generate(int numRows) { if (numRows < 0) { return null; } List<List<Integer>> pascalTriangle = new ArrayList<List<Integer>>(); for (int i=0; i<numRows; ++i) { if (i == 0) { List<Integer> currTriangle = new ArrayList<Integer>(); currTriangle.add(1); pascalTriangle.add(i, currTriangle); } else { List<Integer> currTriangle = new ArrayList<Integer>(); List<Integer> lastTriangle = pascalTriangle.get(i-1); int lastInteger = 0; for (int j=0; j<lastTriangle.size(); ++j) { currTriangle.add(lastInteger + lastTriangle.get(j)); lastInteger = lastTriangle.get(j); } currTriangle.add(1); pascalTriangle.add(currTriangle); } }// end of for return pascalTriangle; } }
标签:blog io ar java for 2014 on log ad
原文地址:http://blog.csdn.net/yeweiouyang/article/details/40350095