120. Triangle

1 题目理解

Given a triangle array, return the minimum path sum from top to bottom.
For each step, you may move to an adjacent number on the row below.

输入:一个三角形数组List<List> triangle
输出:从顶层走到底层最小路径和
规则:每次只能从上一层走到下一层的相邻单元。相邻单元是指与上一层下标相同,或者上一层下标+1。

Example 1:
Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Explanation: The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

2 解题

2.1 动态规划

2
3 4
6 5 7
4 1 8 3

用dp[i][j]表示达到第i层第j列位置的最小路劲和。
根据题意,要想达到(i,j)只能通过(i-1,j)或者(i-1,j-1)两种方式达到。
那动态转移方程是: d p [ i ] [ j ] = m i n ( d p [ i − 1 ] [ j − 1 ] , d p [ i − 1 ] [ j ] ) + t r i a n g l e [ i ] [ j ] dp[i][j] =min(dp[i-1][j-1],dp[i-1][j])+triangle[i][j] dp[i][j]=min(dp[i1][j1],dp[i1][j])+triangle[i][j]
初始化条件:dp[0][0]=triangle[0][0]
最后结果是在最后一层数组中查找最大值

class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int m = triangle.size();
        int n = triangle.get(m-1).size();
        int[][] dp = new int[m][n];
        dp[0][0] = triangle.get(0).get(0);
        for(int i=1;i<m;i++){
            int len = triangle.get(i).size();
            for(int j=0;j<len;j++){
            	dp[i][j] = Integer.MAX_VALUE;
            	if(j==0) {
            		dp[i][j] = dp[i-1][j]+triangle.get(i).get(j);
            	}else if(j==len-1){
                    dp[i][j] = dp[i-1][j-1]+triangle.get(i).get(j);
                }else{
                    dp[i][j] = Math.min(dp[i-1][j],dp[i-1][j-1])+triangle.get(i).get(j);
                }
                
            }
        }
        int min = dp[m-1][0];
        for(int j=1;j<n;j++){
            min = Math.min(min,dp[m-1][j]);
        }
        return min;
    }
}

时间复杂度: O ( n 2 ) O(n^2) O(n2),n是triangle的长度。

2.2 优化空间

仔细观察我们发现动态转移方程只与i-1有关系,所以我们可以使用滚动数组来实现。

class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int m = triangle.size();
        int n = triangle.get(m-1).size();
        int[] dp = new int[1];
        dp[0] = triangle.get(0).get(0);
        for(int i=1;i<m;i++){
            int len = triangle.get(i).size();
            int[] newDp = new int[len];
            for(int j=0;j<len;j++){
            	newDp[j] = Integer.MAX_VALUE;
            	if(j==0) {
            		newDp[j] = dp[j]+triangle.get(i).get(j);
            	}else if(j==len-1){
                    newDp[j] = dp[j-1]+triangle.get(i).get(j);
                }else{
                    newDp[j] = Math.min(dp[j],dp[j-1])+triangle.get(i).get(j);
                }
                
            }
            dp = newDp;
        }
        int min = dp[0];
        for(int j=1;j<dp.length;j++){
            min = Math.min(min,dp[j]);
        }
        return min;
    }
}

2.3进一步优化空间

方程中计算j的时候只与j和j-1相关。如果我们的只有一个数组int[] dp,那我们可以从右到左计算。
我们计算dp[j]的时候使用了dp[j]和dp[j-1],
在计算dp[j-1]的时候使用dp[j-1]和dp[j-2],与dpp[j]无关,所以可以这样做。

class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int m = triangle.size();
        int n = triangle.get(m-1).size();
        int[] dp = new int[n];
        dp[0] = triangle.get(0).get(0);
        for(int i=1;i<m;i++){
            int len = triangle.get(i).size();
            dp[i] = dp[i-1] + triangle.get(i).get(i);
            for(int j=i-1;j>0;j--){
                dp[j] = Math.min(dp[j],dp[j-1])+triangle.get(i).get(j);
            }
            dp[0] += triangle.get(i).get(0);
        }
        int min = dp[0];
        for(int j=1;j<dp.length;j++){
            min = Math.min(min,dp[j]);
        }
        return min;
    }
}
Serpinski's Triangle and Carpet are two famous fractal patterns named after the Polish mathematician Wacław Sierpiński. These patterns are created through a recursive process of dividing shapes into smaller copies of themselves. 1. Serpinski's Triangle: Serpinski's Triangle is a fractal pattern that starts with an equilateral triangle. In each iteration, the triangle is divided into four smaller triangles by connecting the midpoints of its sides. The central triangle is then removed, and the process is repeated for the remaining three triangles. This recursive division continues indefinitely, creating a pattern of smaller triangles within the original triangle. 2. Serpinski's Carpet: Serpinski's Carpet is a fractal pattern that starts with a square. In each iteration, the square is divided into nine smaller squares by removing the central square and dividing the remaining eight squares into nine equal-sized squares. The process is then repeated for each of the remaining eight squares. This recursive division continues indefinitely, creating a pattern of smaller squares within the original square. Both Serpinski's Triangle and Carpet exhibit self-similarity, meaning that they contain smaller copies of themselves at different scales. These fractal patterns have been widely studied and appreciated for their intricate and visually appealing structures. If you want to generate Serpinski's Triangle or Carpet using Python, you can use recursion and graphical libraries like Turtle or Matplotlib to draw the patterns. Here's an example code snippet for generating Serpinski's Triangle using Turtle: ```python import turtle def draw_triangle(length, depth): if depth == 0: for _ in range(3): turtle.forward(length) turtle.left(120) else: draw_triangle(length / 2, depth - 1) turtle.forward(length / 2) draw_triangle(length / 2, depth - 1) turtle.backward(length / 2) turtle.left(60) turtle.forward(length / 2) turtle.right(60) draw_triangle(length / 2, depth - 1) turtle.left(60) turtle.backward(length / 2) turtle.right(60) # Set up the turtle turtle.speed(0) turtle.penup() turtle.goto(-200, -200) turtle.pendown() # Draw Serpinski's Triangle draw_triangle(400, 4) # Hide the turtle turtle.hideturtle() # Keep the window open turtle.done() ``` This code will generate Serpinski's Triangle with a depth of 4. You can adjust the depth parameter to control the level of detail in the pattern.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值