LeetCode——第118题:帕斯卡三角形(杨辉三角)

题目:

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

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

示例:

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

代码:

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

/**
 * @作者:dhc
 * @创建时间:20:32 2018/8/1
 * @描述:118.杨辉三角(帕斯卡三角形)
 */
public class OneHundredAndEighteen {
    public static List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        for(int i = 0;i < numRows;i++){
            List<Integer> tem = new ArrayList<Integer>();
            for(int j = 0;j <= i;j++){
                if(j == 0 || j == i){
                    tem.add(1);
                }else{

                    tem.add((int)result.get(i-1).get(j) + (int)result.get(i-1).get(j - 1));
                }
            }
            result.add(tem);
            tem = new ArrayList<Integer>();
        }
        return result;
    }

    public static void main(String[] args) {
        List<List<Integer>> re = generate(5);
        for (int i = 0; i < re.size(); i++) {
            List<Integer> tem = re.get(i);
            for (int j = 0; j < tem.size(); j++) {
                System.out.print(tem.get(j)+" ");
            }
            System.out.println();
        }
    }
}
发布了75 篇原创文章 · 获赞 13 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章