LeetCode 1029. Two City Scheduling

原题链接在这里: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 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12321484.html