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]
]

杨辉三角,题目本身很简单。具体我就不解释了,

首先简单写一下自己的想法。

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++同样的思想效率会更高。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值