leetcode-第118题-杨辉三角

博主并没有什么算法基础,所以写的不好,勿喷,抛砖引玉,欢迎交流,感谢。

//给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。 
// 在杨辉三角中,每个数是它左上方和右上方的数的和。
// 示例:
// 输入: 5
//输出:
//[
//     [1],
//    [1,1],
//   [1,2,1],
//  [1,3,3,1],
// [1,4,6,4,1]
//] 
// Related Topics 数组 
// 👍 349 👎 0


package com.zqh.leetcode.editor.cn;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//Java:杨辉三角
public class P118PascalsTriangle {
    public static void main(String[] args) {
        Solution solution = new P118PascalsTriangle().new Solution();
        System.out.println(solution.generate(5));
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public List<List<Integer>> generate(int numRows) {
            List<List<Integer>> result = new ArrayList<>(numRows);
            if (0 == numRows) {
                return result;
            }
            List<Integer> array = Arrays.asList(1);
            result.add(array);
            if (1 == numRows) {
                return result;
            }
            triangle(result, array, numRows, 2);
            return result;
        }

        /**
         * @param result         结果集
         * @param upperArray     上一层的结果
         * @param totalNumRows   总行数
         * @param currentNumRows 当前行数
         */
        public void triangle(List<List<Integer>> result, List<Integer> upperArray, int totalNumRows, int currentNumRows) {
            List<Integer> currentArray = new ArrayList<>(currentNumRows);
            for (int i = 0; i < currentNumRows; i++) {
                if (i == 0 || i == currentNumRows - 1) {
                    // 如果是首位或末尾,就直接设置1
                    currentArray.add(1);
                    continue;
                }
                // 其他的就拿取上一层结果的前一坐标值+当前坐标值
                currentArray.add(upperArray.get(i - 1) + upperArray.get(i));
            }
            result.add(currentArray);
            if (totalNumRows != currentNumRows) {
                // 还没到指定行数,就继续循环
                triangle(result, currentArray, totalNumRows, ++currentNumRows);
            }
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值