您的位置:首页 > 编程语言 > PHP开发

FTPrep, 118 Pascal's Triangle

2017-10-08 04:08 363 查看
层序遍历的变体,根据上一层生成下一层,list in list题型。不多废话了,之间看代码吧:

class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result= new ArrayList<List<Integer>>();
if(numRows==0) return result;
for(int i=1; i<=numRows; i++){
List<Integer> newRow = new ArrayList<Integer>();
newRow.add(1);
for(int j=1; j<=i-2; j++){ // j is the index, it is good to use this way.
if(result.get(0)!=null){ // !!! Attension, for the 1st row, the result is still empty.
newRow.add(result.get(result.size()-1).get(j)+result.get(result.size()-1).get(j-1));
}
}
if(i!=1) newRow.add(1); // !!! Attension, for the 1st row again, only a single number.
result.add(newRow);
}
return result;

}
}

// 根据上面的结论,其实把 numRows==1 单独拿出来更加好操作了。面试的时候可以这样做,解释清楚就可以了。
// 基本思路是,每一行的首尾都是1,只要处理中间的 (n-2)个数就ok了,这(n-2)个数是很上一行的(n-2)个数match上的,具体的是上一行的 (kth)+(k-1 th)= 这一行的(kth)
// 按照这个通项公式写就okay了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: