iT邦幫忙

2025 iThome 鐵人賽

DAY 0
0
自我挑戰組

Leetcode30天挑戰系列 第 21

Day21-Triangle

  • 分享至 

  • xImage
  •  

今天的題目為120.Triangle,今天的題目是在叫我們從頂端(第一層)開始往下走到最底層,每一步只能往下一層的相鄰位置移動,也就是說:如果你現在在第i層的第j個元素,你下一步可以走到第i+1層的第j或第j+1個元素,要找出所有可能路徑中,總和最小的那一條路徑,並回傳這個最小總和。

以下為程式碼:

class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int n = triangle.size();

        for (int i = n - 2; i >= 0; i--) {
            for (int j = 0; j < triangle.get(i).size(); j++) {
                int belowLeft = triangle.get(i + 1).get(j);
                int belowRight = triangle.get(i + 1).get(j + 1);
                int minPath = Math.min(belowLeft, belowRight);
                triangle.get(i).set(j, triangle.get(i).get(j) 
                + minPath);
            }
        }

        return triangle.get(0).get(0);
    }
}

今天的有一點點難,但好像又在我可以接受的範圍,原本看到三角形的路徑和的時候有一點困惑,但後來釐清之後就豁然開朗。


上一篇
Day20-Pascal's Triangle II
下一篇
Day22-Best Time to Buy and Sell Stock
系列文
Leetcode30天挑戰30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言