Java刷題隨筆---118. 楊輝三角

118. 楊輝三角 - 力扣(LeetCode) (leetcode-cn.com)

難度:簡單
題目描述:給定一個(gè)非負(fù)整數(shù) numRows,生成「楊輝三角」的前 numRows 行。
在「楊輝三角」中,每個(gè)數(shù)是它左上方和右上方的數(shù)的和。

Leetcode118.gif

分析

楊輝三角近似看成如下所示的例圖:
*
* *
* * *
所以楊輝三角可以表示為:
1
1 1
1 2 1
設(shè)置兩個(gè)指針一個(gè)為行指針(row),一個(gè)為列指針(column)
楊輝三角中的元素可以分為兩種情況:
1- 當(dāng)column==0或column==row時(shí),值為1
2- 當(dāng)為其他情況時(shí),array[row][column] = array[row-1][column-1] + array[row-1][column]

解題

class Solution {
        public List<List<Integer>> generate(int numRows) {

            List<List<Integer>> result = new ArrayList<>();

            for (int i = 0; i < numRows; i++) {
                List<Integer> currentList = new ArrayList<>();
                for (int j = 0; j <= i; j++) {
                    if (i == j || j == 0) {
                        currentList.add(1);
                    } else {
                        currentList.add(result.get(i - 1).get(j - 1) + result.get(i - 1).get(j));
                    }
                }
                result.add(currentList);
            }

            return result;
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容