楊輝三角 II
題目描述:給定一個非負(fù)索引 k,其中 k ≤ 33桦山,返回楊輝三角的第 k 行本慕。
在楊輝三角中,每個數(shù)是它左上方和右上方的數(shù)的和唱矛。
示例說明請見LeetCode官網(wǎng)。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/pascals-triangle-ii/
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有井辜。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán)绎谦,非商業(yè)轉(zhuǎn)載請注明出處。
解法一:暴力破解法
首先粥脚,當(dāng)numRows等于0或者1時窃肠,直接返回固定的前兩行;
當(dāng)numRows大于等于2時刷允,從第2行開始處理冤留,假如當(dāng)前行是cur,上一行是last:
- cur的第一個數(shù)字是1树灶;
- cur的第二個數(shù)字到倒數(shù)第二個數(shù)字(j)是last行的相應(yīng)位置(j-2和j-1)的和纤怒;
- cur的最后一個數(shù)字是1;
- 將last設(shè)置為cur天通。
最后返回cur泊窘。
備注:方法跟該題 LeetCode-118-楊輝三角 完全一樣。
import java.util.ArrayList;
import java.util.List;
public class LeetCode_119 {
public static List<Integer> getRow(int rowIndex) {
List<Integer> one = new ArrayList<>();
one.add(1);
if (rowIndex == 0) {
return one;
}
List<Integer> two = new ArrayList<>();
two.add(1);
two.add(1);
if (rowIndex == 1) {
return two;
}
List<Integer> last = two;
List<Integer> cur = new ArrayList<>();
for (int i = 2; i <= rowIndex; i++) {
cur = new ArrayList<>();
cur.add(1);
for (int j = 1; j < i; j++) {
cur.add(last.get(j - 1) + last.get(j));
}
cur.add(1);
last = cur;
}
return cur;
}
public static void main(String[] args) {
for (Integer integer : getRow(3)) {
System.out.print(integer + " ");
}
}
}
【每日寄語】 愿你所得過少時土砂,不會終日憤憤;愿你所得過多時谜洽,不必終日惶恐萝映。