杨辉三角的实现(非负整数)

本文介绍了一种使用链表数据结构生成杨辉三角的方法。通过Java编程语言,实现了从输入行数到生成对应行数的杨辉三角的完整过程。代码首先检查输入的有效性,然后初始化前两行,接着通过迭代生成后续每一行,每行由1开始,中间元素为上一行相邻两元素之和,最后再次以1结束。

用链表来实现,

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Generate {

    public static List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<>();

        if(numRows <= 0) {
            return result;
        }

        ArrayList<Integer> firstLine = new ArrayList<>();
        firstLine.add(1);
        result.add(firstLine);
        if(numRows == 1) {
            return result;
        }

        ArrayList<Integer>secondLine = new ArrayList<>();
        secondLine.add(1);
        secondLine.add(1);
        result.add(secondLine);
        if(numRows == 2) {
            return result;
        }

        for (int row = 3; row <= numRows ; row++) {

            List<Integer> prevLine = result.get(row-1-1);
            List<Integer> curLine = new ArrayList<>();

            curLine.add(1);

            for(int col = 2;col <= row-1; col++) {
                int tmp1 = prevLine.get(col-1-1);
                int tmp2 = prevLine.get(col-1);
                curLine.add(tmp1 + tmp2);
            }

            curLine.add(1);
            result.add(curLine);
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int i = scanner.nextInt();
        System.out.println(generate(i));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值