LeetCode --- 字符串、數(shù)組
簡(jiǎn)書專欄:http://www.itdecent.cn/nb/41796568
知乎專欄:https://zhuanlan.zhihu.com/c_174823416
一、題目描述
來源:力扣(LeetCode)
給定一個(gè)非負(fù)整數(shù) numRows,生成楊輝三角的前 numRows 行。
在楊輝三角中,每個(gè)數(shù)是它左上方和右上方的數(shù)的和。
示例:
輸入: 5
輸出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
要求實(shí)現(xiàn)函數(shù):
public List<List<Integer>> generate(int numRows) {}
二、實(shí)現(xiàn)思路以及代碼
可以根據(jù)題意得知,每一行都是由前一行依次相加得到的,且每一行的首尾都是由1構(gòu)成,所以要得到當(dāng)前行,只需要遍歷上一行,依次相加即可得到中間部分的值,兩端是1。從代碼中理解更為容易。
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
if (numRows <= 0) {
return result;
}
result.add(new ArrayList<>());
result.get(0).add(1);
for (int i = 2; i <= numRows; i++) {
ArrayList<Integer> aList = new ArrayList<>();
//首字母為1
aList.add(1);
//添加中間元素
for(int j = 1; j < i - 1; j++) {
//i-2是因?yàn)榈趇行的數(shù)由第i-1行確定,存放在List中的i-2位置
aList.add(result.get(i - 2).get(j - 1) + result.get(i - 2).get(j));
}
//添加末尾元素
aList.add(1);
result.add(aList);
}
return result;
}
三、測(cè)試代碼
public static void main(String[] args) {
List<List<Integer>> list = generate(6);
for (List<Integer> te : list) {
for(int cur : te) {
System.out.print(cur + " ");
}
System.out.println();
}
}
輸出結(jié)果為:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1