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了
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了
相关文章推荐
- FTPrep, 119 Pascal's Triangle II
- The Solution to Leetcode 118 Pascal's Triangle
- LeetCode 118 Pascal's Triangle
- LeetCode - 118/119 - Pascal's Triangle
- 【一天一道LeetCode】#118. Pascal's Triangle
- 118. Pascal's Triangle
- 118. Pascal's Triangle
- 118. Pascal's Triangle
- 118. Pascal's Triangle
- 118. Pascal's Triangle
- 【LeetCode-面试算法经典-Java实现】【118-Pascal's Triangle(帕斯卡三角形)】
- Easy 118题 Pascal's Triangle (may be not easy too for me)
- 118. Pascal's Triangle
- leetcode_question_118 Pascal's Triangle
- Leetcode 118 Pascal's Triangle
- 118 Pascal' Triangle 逻辑已经跟不上了咋整= =
- 118. Pascal's Triangle
- leetcode 118 Pascal's Triangle
- [118] Pascal's Triangle
- 118. Pascal's Triangle