1. 程式人生 > 其它 >LeetCode_118_楊輝三角

LeetCode_118_楊輝三角

技術標籤:LeetCode學習之路leetcode

題目連結

解題思路

  • 在楊輝三角中,每個數是它左上方和右上方的數的和
  • 除了最兩側都是1外,如下動圖所示
  • img

AC程式碼

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>
(); for (int i = 0; i < numRows; i++) { List<Integer> row = new ArrayList<>(); for (int j = 0; j <= i; j++) { if (j == 0 || j == i) row.add(1); else row.add(ans.get(i - 1).get(j - 1
) + ans.get(i - 1).get(j)); } ans.add(row); } return ans; } }

本地測試程式碼

package com.company;

import java.util.ArrayList;
import java.util.List;

public class Solution_118 {
    public static List<List<Integer>> generate(int numRows) {
        List<
List<Integer>> ans = new ArrayList<List<Integer>>(); for (int i = 0; i < numRows; i++) { List<Integer> row = new ArrayList<>(); for (int j = 0; j <= i; j++) { if (j == 0 || j == i) row.add(1); else row.add(ans.get(i - 1).get(j - 1) + ans.get(i - 1).get(j)); } ans.add(row); } return ans; } public static void main(String[] args) { System.out.println(generate(5)); } }