码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 1029. Two City Scheduling

时间:2020-02-17 13:58:18      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:div   java   Plan   any   i++   com   -o   math   cost   

原题链接在这里:https://leetcode.com/problems/two-city-scheduling/

题目:

There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1].

Return the minimum cost to fly every person to a city such that exactly N people arrive in each city.

Example 1:

Input: [[10,20],[30,200],[400,50],[30,20]]
Output: 110
Explanation: 
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.

The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.

Note:

  1. 1 <= costs.length <= 100
  2. It is guaranteed that costs.length is even.
  3. 1 <= costs[i][0], costs[i][1] <= 1000

题解:

Let dp[i][j] denote for the first i + j people, minimum cost to fly i people to A and j people to B.

Then dp[i][j] = min of dp[i - 1][j] + costs[i + j - 1][0], fly i + j - 1 person to A and previous cost to fly i - 1 people to A and j people to B.

and dp[i][j - 1] + costs[i + j - 1][1], fly i + j - 1 person to B and previous cost to fly i people to A and j - 1 people to B.

Time Complexity: O(n ^ 2).

Space: O(n ^ 2).

AC Java:

 1 class Solution {
 2     public int twoCitySchedCost(int[][] costs) {
 3         int n = costs.length / 2;
 4         int [][] dp = new int[n + 1][n + 1];
 5         
 6         for(int i = 1; i <= n; i++){
 7             dp[i][0] = dp[i - 1][0] + costs[i- 1][0];
 8         }
 9         
10         for(int j = 1; j <= n; j++){
11             dp[0][j] = dp[0][j - 1] + costs[j - 1][1];
12         }
13         
14         for(int i = 1; i <= n; i++){
15             for(int j = 1; j <= n; j++){
16                 dp[i][j] = Math.min(dp[i - 1][j] + costs[i + j - 1][0], dp[i][j - 1] + costs[i + j - 1][1]);
17             }
18         }
19         
20         return dp[n][n];
21     }
22 }

 

LeetCode 1029. Two City Scheduling

标签:div   java   Plan   any   i++   com   -o   math   cost   

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12321484.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!