LeetCode 173 Race Course Week

1332. deleted palindromic sequence

You give a string s, it is only by the letter 'a' and 'b' composition. Each time a delete operation can be removed from s the palindromic sequence .

Delete to delete the minimum number of return given string all the characters (the string is empty) of.

"Subsequence" is defined: if a character string can not change the original order by removing some characters get the original string, the string is a sequence of the original string.

"Palindrome" is defined: if a string backward and forward reading is consistent, then the string is a palindrome.

示例 1:

输入:s = "ababa"
输出:1
解释:字符串本身就是回文序列,只需要删除一次。

示例 2:

输入:s = "abb"
输出:2
解释:"abb" -> "bb" -> "". 
先删除回文子序列 "a",然后再删除 "bb"。

        This problem is very intimidating at first glance, it is tempting to think of the longest palindrome substring such practice, then the dynamic programming operation ...... in fact very simple meal, the most critical is the title tell you the only letters 'a' and 'b' composed , and every time a delete operation can be removed from s the palindromic sequence ( note: sequence refers to a string discontinuous !!! string). And so most only two deletion, delete 'a' + Delete 'b'.

    public int removePalindromeSub(String s) {
        if (s.isEmpty()) {
            return 0;
        }

        StringBuilder builder = new StringBuilder(s);
        if (builder.reverse().toString().equals(s)) {
            return 1;
        }

        return 2;
    }

 

1333. Restaurant filter

Give you a restaurant array of information  restaurants, which   restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You must use the following three filters to filter these restaurant information.

Vegetarian-friendly filter in which  veganFriendly the value can be  true or  false, if it is  true  it means that you should only include  veganFriendlyi as true of restaurants,  false  means may include any restaurant. In addition, we have a maximum price  maxPrice and the maximum distance of  maxDistance two filters, which are considered the maximum price factor and distance factor of the restaurant.

Restaurant returned after filtration  ID , according to the  rating  descending order. If the  rating  the same, then by  id  sort from high to low. For simplicity,  veganFriendlyi and  veganFriendly it is  true  when the value is  1 , is  false  , the value of  0.

示例 1:

输入:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10
输出:[3,1,5] 
解释: 
这些餐馆为:
餐馆 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]
餐馆 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]
餐馆 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]
餐馆 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]
餐馆 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] 
在按照 veganFriendly = 1, maxPrice = 50 和 maxDistance = 10 进行过滤后,我们得到了餐馆 3, 餐馆 1 和 餐馆 5(按评分从高到低排序)。 

        This question is very simple meaning of the questions, the idea is simple. The title is based on the conditions and screening process on it. The difficulty is that many conditions title, if the filter directly in accordance with the conditions, coding is very troublesome, only the layers required determination condition, and to sort. The best practice is to use the Java8 stream operations .

public List<Integer> filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) {
        //传统方法        
//        List<Integer> result = new ArrayList<>();
//        for (int i = 0; i < restaurants.length; i++) {
//            int id = restaurants[i][0];
//            int rating = restaurants[i][1];
//            int friendly = restaurants[i][2];
//            int price = restaurants[i][3];
//            int distance = restaurants[i][4];
//            ...
//            //处理删选条件太多
//        }
        //流处理
        return Arrays.stream(restaurants)
                .filter(array -> veganFriendly == 0 || array[2] == veganFriendly)  //过滤
                .filter(array -> array[3] <= maxPrice)
                .filter(array -> array[4] <= maxDistance)
                .sorted((x, y) -> {
                    if (x[1] - y[1] != 0) {  //排序
                        return y[1] - x[1];
                    } else {
                        return y[0] - x[0];
                    }
                })
                .map(x -> x[0])  //映射:将元素映射成另外一个元素
                .collect(Collectors.toList());  //将结果转换为List
    }

 

1334. Minimum distance within a threshold of the neighboring cities

There are n cities, according to from 0 to n-1 number. Edges give you an edge array, wherein the weighting between the bidirectional edges [i] = [fromi, toi, weighti] Representative Fromi two cities and toi sides, the threshold value is an integer from distanceThreshold.

Some can return path to the minimum number of other cities, and the path from the largest to distanceThreshold city. If more than one such city, the largest city in the number returned.

Note that the connection path of the city i and j is equal to a distance along the path of the sum of the weights of all edges and.

输入:n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
输出:3
解释:城市分布图如上。
每个城市阈值距离 distanceThreshold = 4 内的邻居城市分别是:
城市 0 -> [城市 1, 城市 2]   // 0 -> 3 距离大于4,不符合
城市 1 -> [城市 0, 城市 2, 城市 3] 
城市 2 -> [城市 0, 城市 1, 城市 3] 
城市 3 -> [城市 1, 城市 2]   // 3 -> 0 距离大于4,不符合
城市 0 和 3 在阈值距离 4 以内都有 2 个邻居城市,但是我们必须返回城市 3,因为它的编号最大。

analysis:

        This problem is typical of the shortest path problem , this problem usually has two solutions: Floyd algorithm and Dijkstra's algorithm , Floyd algorithm may be employed according to the present problem.

Floyd algorithm:

        Floyd algorithm known as interpolation point method, in which the core idea of the algorithm is dynamic programming .

Algorithm steps:

  • Initialization distance matrix D [n] [n] by known conditions, wherein D [i] [j] denotes the distance vertex i to vertex j.
  • n vertices sequentially as the insertion point, e.g., k is one vertex, D [i] [k] + D [k] [j] <D [i] [j], it means that node i through the vertex k longer reach j than directly to the j should be close. Therefore Update D [i] [j]: D [i] [j] = D [i] [k] + D [k] [j].
  • Can be summed to obtain the state transition equation: D [i] [j] = min (D [i, k] + D [k, j], D [i, j]);

Core code:

// Floyd算法
for (int k = 0; k < n; k++) {
    // n个顶点依次作为插入点
    // 注意插点k是放在第一层循环
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            // 遍历各个顶点之间的距离,并用插入点进行更新
            D[i][j] = min(D[i][k]+D[k][j], D[i][j]);
        }
    }
}

The title complete code is as follows:

    public int findTheCity(int n, int[][] edges, int distanceThreshold) {
        int[][] map = new int[n][n];
        for (int i = 0; i < edges.length; i++) {
            map[edges[i][0]][edges[i][1]] = edges[i][2];
            map[edges[i][1]][edges[i][0]] = edges[i][2];
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (i != j) {
                    if (map[i][j] == 0) {
                        map[i][j] = 100000;  //注意:此处不能设置为Integer.MAX_VALUE, 计算会导致越界造成不可知的结果
                    }
                }
            }
        }
        for (int k = 0; k < n; k++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    map[i][j] = Math.min(map[i][j], map[i][k] + map[k][j]);
                }
            }
        }
        int mind = n;  //当前到达其他城市的最少数目
        int min = Integer.MAX_VALUE;  //符合要求的城市编号
        for (int i = 0; i < n; i++) {
            int count = 0;  //到达其他城市的数目
            for (int j = 0; j < n; j++) {
                int a = map[i][j];
                if (a <= distanceThreshold) {
                    count++;
                }
            }
            if (count <= mind) {
                mind = count;
                min = i;
            }
        }
        return min;
    }

 

1335. Minimum difficulty of the work plan

You need to develop a d-day work schedule. There is between jobs depend, in order to perform the work item i, j you must complete all work items (0 <= j <i).

You need to complete at least one mission a day. Overall difficulty of the work plan is that the difficulty of d day and every day, and difficulty of the work is the most difficult day's work should be completed the same day.

JobDifficulty give you an array of integers and an integer d, representing the number of days required and the difficulty of the work plan. I work item difficulty is jobDifficulty [i].

Returns the minimum difficulty of the entire work program. If you can not develop a work plan, -1 is returned.

示例 1:

输入:jobDifficulty = [6,5,4,3,2,1], d = 2
输出:7
解释:第一天,您可以完成前 5 项工作,总难度 = 6.
第二天,您可以完成最后一项工作,总难度 = 1.
计划表的难度 = 6 + 1 = 7 

analysis:

        This problem is typical of the dynamic programming problem.

        dp [i] [j]: indicates the minimum days to complete before i difficult task required before j

        There are many options, may be the first i-1 k-1 days to complete the task (since it is completed at least one, k-1> = i- 1 per day), and then completing the first day i k, k + 1,. .., I task, the required degree of difficulty: dp [i-1] [ k-1] + max {jobDifficulty [k], jobDifficulty [k + 1], ..., jobDifficulty [i]}
        in order to complete the minimum degree of difficulty, we can select from the smallest, namely:

       dp[i][j] = min{ dp[i-1][k-1] + max{ jobDifficulty[k], jobDifficulty[k+1], ..., jobDifficulty[i] } }, i <= k <= jobDiffculty.size()。

public int minDifficulty(int[] jobDifficulty, int d) {
        if (d > jobDifficulty.length) {
            return -1;
        }
        int LENGTH = jobDifficulty.length;
        int[][] dp = new int[d][LENGTH];
        for (int i = 0; i < d; i++) {
            Arrays.fill(dp[i], Integer.MAX_VALUE / 2);
        }
        int preDif = 0;  //工作难度
        for(int i = 0; i < LENGTH; i++){
            preDif = Math.max(preDif, jobDifficulty[i]);
            dp[0][i] = preDif;
        }
        for(int i = 1; i < d; i++){  //前i天
            for(int j = i; j < LENGTH; j++){  //前j项任务
                preDif = jobDifficulty[j];
                for(int k = j; k >= i; k--){  //前k项任务
                    preDif = Math.max(preDif, jobDifficulty[k]);
                    dp[i][j]= Math.min(dp[i][j], dp[i-1][k-1] + preDif);
                }
            }
        }
        return dp[d-1][LENGTH-1];
    }

 

Published 69 original articles · won praise 69 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_34519487/article/details/104429595