基于Java實現(xiàn)楊輝三角 LeetCode Pascal's Triangle
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]
]
這道題比較簡單, 楊輝三角, 可以用這一列的元素等于它頭頂兩元素的和來求.
數(shù)學(xué)扎實的人會看出, 其實每一列都是數(shù)學(xué)里的排列組合, 第4行, 可以用 C30 = 0 C31=3 C32=3 C33=3 來求
import java.util.ArrayList; import java.util.List; public class Par { public static void main(String[] args) { System.out.println(generate(1)); System.out.println(generate(0)); System.out.println(generate(2)); System.out.println(generate(3)); System.out.println(generate(4)); System.out.println(generate(5)); } public static List<List<Integer>> generate(int numRows) { List<List<Integer>> result = new ArrayList<List<Integer>>(numRows); for (int i = 0; i < numRows; i++) { List<Integer> thisRow = new ArrayList<Integer>(i); thisRow.add(1); int temp = 1; int row = i; for (int j = 1; j <= i; j++) { temp = temp * row-- / j ; thisRow.add(temp); } result.add(thisRow); } return result; } }
以上內(nèi)容給大家介紹了基于Java實現(xiàn)楊輝三角 LeetCode Pascal's Triangle的相關(guān)知識,希望大家喜歡。
相關(guān)文章
Java中Boolean與字符串或者數(shù)字1和0的轉(zhuǎn)換實例
下面小編就為大家?guī)硪黄狫ava中Boolean與字符串或者數(shù)字1和0的轉(zhuǎn)換實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07Java httpClient連接池支持多線程高并發(fā)的實現(xiàn)
本文主要介紹了Java httpClient連接池支持多線程高并發(fā)的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08java復(fù)制文件的4種方式及拷貝文件到另一個目錄下的實例代碼
這篇文章主要介紹了java復(fù)制文件的4種方式,通過實例帶給大家介紹了java 拷貝文件到另一個目錄下的方法,需要的朋友可以參考下2018-06-06Spring Boot整合logback一個簡單的日志集成架構(gòu)
今天小編就為大家分享一篇關(guān)于Spring Boot整合logback一個簡單的日志集成架構(gòu),小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01