Pascal's Triangle

来源:互联网 发布:table2excel.js 编辑:程序博客网 时间:2024/06/06 12:50

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 {    public List<List<Integer>> generate(int numRows) {        List<List<Integer>> lst = new ArrayList<List<Integer>>();        List<Integer> last = null;        for(int i = 1;i <= numRows;i++){        List<Integer> temp = new ArrayList<Integer>();            for(int j = 0;j < i;j++){                if(j == 0){                   temp.add(1);                }else if(j == i-1){                    temp.add(1);                    last = temp;                }else{                    int num = last.get(j-1)+last.get(j);                    temp.add(num);                }            }            lst.add(temp);        }        return lst;    }}

效率不高。只战胜了27.62%,我们尝试一下减少判断的部分代码。

public class Solution {    public List<List<Integer>> generate(int numRows) {        List<List<Integer>> lst = new ArrayList<List<Integer>>();        if(numRows < 1){            return lst;         }        List<Integer> last = null;        List<Integer> temp = new ArrayList<Integer>();        temp.add(1);        last = temp;        lst.add(temp);        for(int i = 2;i <= numRows;i++){        temp = new ArrayList<Integer>();        temp.add(1);            for(int j = 1;j<i-1;j++){                int num = last.get(j-1)+last.get(j);                temp.add(num);            }            temp.add(1);            last = temp;            lst.add(temp);        }        return lst;    }}

效率还是不变的,显然这是这个思想的极限了。当然啦,递归也是可以实现的。

public class Solution {    public List<List<Integer>> generate(int numRows) {        List<List<Integer>> lst = new ArrayList<List<Integer>>();        if(numRows < 1){            return lst;         }        List<Integer> temp = new ArrayList<Integer>();        temp.add(1);        lst.add(temp);        generate(lst,temp,numRows+1,2);        return lst;    }    public void generate(List<List<Integer>> lst, List<Integer> last, int numRows,int n) {          if(n == numRows){              return;           }else{              List<Integer> temp = new ArrayList<Integer>();              temp.add(1);              int len = n-1;              for(int i = 1;i <len;i++){                  temp.add(last.get(i-1)+last.get(i));              }              temp.add(1);              lst.add(temp);              generate(lst,temp,numRows,n+1);              return;          }     }}
此外C++同样的思想效率会更高。

0 0