Pascal's Triangle I && Pascal's Triangle II (see the similarities yourself)


  • 0
    I

    Pascal I :

    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> list = new ArrayList<>();
        List<Integer> row, pre = null;
        for(int i = 0; i < numRows ; i++){
            row = new ArrayList<>();
            for(int j = 0; j <= i; j++){
                row.add(j == 0 || j == i ? 1 : pre.get(j-1) + pre.get(j));
            }
            list.add(pre = row);
            
        }
        return list;
    }
    

    Pascal II :

    public List<Integer> getRow(int rowIndex) {
       List<List<Integer>> res = new ArrayList<>();
       List<Integer> row, pre = null;
       for (int i = 0; i <= rowIndex; i++) {
          row = new ArrayList<>();
          for (int j = 0; j <= i; j++)
             row.add(j == 0 || i == j ? 1 : pre.get(j-1) + pre.get(j));
          res.add(pre = row);
       }
       return res.get(res.size() - 1);
    }

Log in to reply
 

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