基于Java實(shí)現(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í)的人會看出, 其實(shí)每一列都是數(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實(shí)現(xiàn)楊輝三角 LeetCode Pascal's Triangle的相關(guān)知識,希望大家喜歡。
相關(guān)文章
Gradle相對于Maven有哪些優(yōu)點(diǎn)
這篇文章主要介紹了Gradle相對于Maven有哪些優(yōu)點(diǎn),幫助大家選擇合適的自動(dòng)構(gòu)建工具,更好的構(gòu)建項(xiàng)目,感興趣的朋友可以了解下2020-10-10
java靜態(tài)工具類注入service出現(xiàn)NullPointerException異常處理
如果我們要在我們自己封裝的Utils工具類中或者非controller普通類中使用@Autowired注解注入Service或者M(jìn)apper接口,直接注入是報(bào)錯(cuò)的,因Utils用了靜態(tài)方法,我們無法直接用非靜態(tài)接口的,遇到這問題,我們要想法解決,下面小編就簡單介紹解決辦法,需要的朋友可參考下2021-09-09
springcloud項(xiàng)目占用內(nèi)存好幾個(gè)G導(dǎo)致服務(wù)器崩潰的問題
這篇文章主要介紹了springcloud項(xiàng)目占用內(nèi)存好幾個(gè)G導(dǎo)致服務(wù)器崩潰的問題,本文給大家分享解決方案供大家參考,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
list集合去除重復(fù)對象的實(shí)現(xiàn)
下面小編就為大家?guī)硪黄猯ist集合去除重復(fù)對象的實(shí)現(xiàn)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-01-01
關(guān)于java中@Async異步調(diào)用詳細(xì)解析附代碼
本文主要介紹了java關(guān)于@Async異步調(diào)用詳細(xì)解析附代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07

