Pascal's Triangle

来源:互联网 发布:怎么申请淘宝网账号 编辑:程序博客网 时间:2024/04/30 01:27

Pascal's Triangle


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]]
Java代码:

public class Solution {    public List<Integer> getRow(int rowIndex) {          List list = new ArrayList<Integer>();              if(0 == rowIndex)              {                  list.add(1);                  return list;              }                            if(1 == rowIndex)              {                  list.add(1);                  list.add(1);                  return list;              }              List list_tmp = getRow(rowIndex-1);              list.add(1);              Iterator ite =list_tmp.iterator();              int tmp =0;              int tmp_2=0;              tmp = (Integer)ite.next();              while(ite.hasNext())              {                  tmp_2 = (Integer)ite.next();                  list.add(tmp+tmp_2);                  tmp = tmp_2;              }              list.add(1);              return list;      }      public List<List<Integer>> generate(int numRows) {        List list = new ArrayList<List>();          for(int i=0;i<numRows;i++)        {            list.add(getRow(i));        }        return list;    }}

上述代码是根据Pascal's Triangle II 修改的,代码上有可以剪枝的地方

 

0 0
原创粉丝点击