My AC java solution with explanation


  • 0
    S

    the first and second row are all 1s.
    from the third row, the first and last element is 1;
    row[j] = pre[j-1] + pre[j] where 1<=j<=row.length-2 and pre is the one upper level row

    public class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> results = new ArrayList<List<Integer>>();
        Integer[] pre = new Integer[]{1,1};
        for(int i=1;i<=numRows;i++)
        {
            
            if(i==1) results.add(Arrays.asList(1));
            else if(i==2) results.add(Arrays.asList(pre));
            else
            {
                Integer[] row = new Integer[i];
                row[0]=1;
                row[i-1]=1;
                for(int j=1;j<i-1;j++)
                {
                    row[j]=pre[j-1]+pre[j];
                }
                results.add(Arrays.asList(row));
                pre=row;
            }
        }
        return results;
        
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.