数组处理:118

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]


public class Solution {//逐个算每个值,每行的第一个和最后一个都是1,其余的 K(i)(j)=K(i-1)(j-1)+K(i-1)(j) 
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> listReturn = new ArrayList<List<Integer>>();
        for(int i=0;i<numRows;i++){
            List<Integer> tempList= new ArrayList<Integer>();
             for(int j=0;j<=i;j++){
                   if(j==0||j==i)tempList.add(1);
                   else tempList.add(listReturn.get(i-1).get(j-1)+listReturn.get(i-1).get(j));
               }
            listReturn.add(tempList);
        }
        return listReturn;
    }
}

每行都可以这么算,没必要第1行、第二行特殊处理,像这样:

public class Solution {//算法1击败了36%,这个击败了2%,= = 
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> listReturn = new ArrayList<List<Integer>>();
        for(int i=0;i<numRows;i++){
            List<Integer> tempList= new ArrayList<Integer>();
            if(i==0)tempList.add(1);
            if(i==1){
                tempList.addAll(listReturn.get(0));
                tempList.add(1);
            }
            if(i>=2){
               for(int j=0;j<=i;j++){
                   if(j==0)tempList.add(1);
                   else if(j==i)tempList.add(1);
                   else tempList.add(listReturn.get(i-1).get(j-1)+listReturn.get(i-1).get(j));
               }
             }
            
            listReturn.add(tempList);
        }
        return listReturn;
    }
}
原文地址:https://www.cnblogs.com/lucky-star-star/p/5054430.html