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

题目链接

先占坑想想~~

你可能感兴趣的:(比赛套题)