leetcode.118 杨辉三角

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

思路:当 numRows 为 1 或者 2 的时候,值是固定的,分别是[ [1] ],[ [ 1 ] ,[ 1 ,1 ]],而从第三行中间的数是第二行的两数之和

有 ,使用一个数组保存上一行的值,并且使用另外的数组记录下要保存的值。

代码:

class Solution {
    public List<List<Integer>> generate(int numRows) {
            if(numRows < 0) return null;
            List<List<Integer>> list = new ArrayList();
            if(numRows >= 1){
                List<Integer> data = new ArrayList();
                data.add(1);
                list.add(data);
        }
            if(numRows >= 2){
                List<Integer> data = new ArrayList();
                data.add(1);
                data.add(1);
                list.add(data);
        }
            if(numRows >= 3){
         
                for(int i = 3;i <= numRows;i++){
                    List<Integer> data = new ArrayList();
                    List<Integer> prev = list.get(i-2);
                    data.add(1);
                    for(int j = 2;j <= i-1 ;j++){
                           data.add(prev.get(j-2) + prev.get(i-1);
                    }
                    data.add(1);
                    list.add(data);
             }
         }
        return list;       
    }
}

解法二:使用二维数组递归实现,

public static int[][] yanghui(int n) {
		if (n == 1)  // 递归条件出口
			return new int[][] { { 1 } };
		if (n == 2)   // 递归条件出口
			return new int[][] { { 1 }, { 1, 1 } };
        // n > 3时的情况
		int[][] result = new int[n][];
		result[0] = new int[] { 1 };
		result[1] = new int[] { 1, 1 };
         // 动态计算数组的值
		for (int i = 2; i < n; i++) {
			result[i] = new int[i + 1];
			result[i][0] = 1;
			result[i][i] = 1;
			for (int j = 1; j < i; j++) {
				result[i][j] = result[i - 1][j] + result[i - 1][j - 1];
			}
		}
		return result;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值