Leet Code 第 135 場周賽

5051. 有效的迴旋鏢

題目鏈接

構建兩個向量,判斷向量是否平行即可。

class Solution {
    public boolean isBoomerang(int[][] points) {
        int a = points[0][0]-points[1][0];
        int b = points[0][1]-points[1][1];
        int c = points[2][0]-points[1][0];
        int d = points[2][1]-points[1][1];
        return a*d != b*c;
    }
}

5050. 從二叉搜索樹到更大和樹

題目鏈接

一開始看中文題意沒看懂,這翻譯也太直了。其實題意就是求二叉搜索樹中序遍歷的序列的後綴和,然後將後綴和的值替換節點的值。直接中序遍歷即可。

Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val.

給出二叉搜索樹的根節點,該二叉樹的節點值各不相同,修改二叉樹,使每個節點 node 的新值等於原樹的值之和,這個值應該大於或等於 node.val

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

class Solution {
    
    int dfs_sum(TreeNode root, int sum)
    {
        if(root == null) return sum;
        sum += root.val;
        sum = dfs_sum(root.left,sum);
        sum = dfs_sum(root.right,sum);
        return sum;
    }
    int dfs(TreeNode root, int sum)
    {
        if(root == null) return sum;
        sum = dfs(root.left,sum);
        int t = root.val;
        root.val = sum;
        sum -= t;
        sum = dfs(root.right,sum);
        return sum;
    }
    public TreeNode bstToGst(TreeNode root) {
       int sum = 0;
       sum = dfs_sum(root,0);
       dfs(root,sum);
       return root;    
    }
}

5047. 多邊形三角剖分的最低得分

題目鏈接

類似於區間DP,dp[i][j] 表示從第i個點到第j個點這(j-i+1)個點構建剖分多邊形的最優解

DP方程爲dp[i][j] = min(dp[i][k]+dp[k][j] + A[i]*A[k]*A[j]) ( i < k < j)

class Solution {
    
    public int inf = 100000000;
    
    public int minScoreTriangulation(int[] A) {
        int n = A.length;
        int[][] dp = new int[n][n];
        for(int i = n-1; i >= 0; i--)
            for(int j = i+1; j < n; j++)
            {
                if(j == i+1) {dp[i][j] = 0;continue;}
                if(dp[i][j] == 0) dp[i][j] = inf;
                 //System.out.println(i+" "+j);
                for(int k = i+1; k < j; k++)
                {
                    dp[i][j] = Math.min(dp[i][j],dp[i][k] + dp[k][j] + A[i]*A[j]*A[k]);
                    //System.out.println(" "+i+j+dp[i][j]+" "+(dp[i][k] + dp[k][j] + A[i]*A[j]*A[k]));
                }
                }
        return dp[0][n-1];
    }
}

5049. 移動石子直到連續 II

題目鏈接

先佔坑想想~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章