(题至)link
leetcode1029 两地调度
公司计划面试 2N 人。第 i 人飞往 A 市的费用为 costs[i][0],飞往 B 市的费用为 costs[i][1]。
返回将每个人都飞到某座城市的最低费用,要求每个城市都有 N 人抵达。
示例:
输入:[[10,20],[30,200],[400,50],[30,20]]
输出:110
解释:
第一个人去 A 市,费用为 10。
第二个人去 A 市,费用为 30。
第三个人去 B 市,费用为 50。
第四个人去 B 市,费用为 20。
最低总费用为 10 + 30 + 50 + 20 = 110,每个城市都有一半的人在面试。
解释
此题使用全排列,列举出所有可能出现的情况A(n)(2n)(使用递归列举出所用情况),从中选择满足条件的最小值,理解起来很容易,但是实现递归过程很麻烦,遇到两个问题:
1.交换两值时,如果是基本类型或者String,则实参不会变(传的是值);(基本类型对应的引用类型如Integer,Double等实参也是不会改变的)
如果是对象集合或者数组,则实参会改变(传的是引用)。
2.java中数组转list使用Arrays.asList(T… a)方法,但是asList接受的参数是一个泛型的变长参数,而基本数据类型是无法泛型化的,不支持基本数据类型转列表
import java.util.ArrayList;
import java.util.List;
public class Solution1029 {
public static int twoCitySchedCost(int[][] costs) {
int lenk = costs.length / 2, res = 0, sum;
List<List<Integer>> list = new ArrayList<List<Integer>>();
int[] arr = new int[costs.length];
for (int i = 0; i < arr.length; i++) arr[i] = i;
fullSort(list, arr, 0, lenk);
for (int i = 0; i < list.size(); i++) {
sum = 0;
System.out.println(list.get(i).contains(1));
for (int j = 0; j < costs.length; j++) {
if (list.get(i).contains(j)) {
sum += costs[j][0];
} else {
sum += costs[j][1];
}
}
System.out.println(sum);
if (res >= sum||res==0) res = sum;
}
return res;
}
public static void fullSort(List<List<Integer>> list, int[] arr, int start, int k) {
if (start == k) {
List lst=new ArrayList<Integer>();
for (int i = 0; i < k; i++) {
lst.add(arr[i]);
}
list.add(lst);
return;
} else {
for (int i = start; i < arr.length; i++) {
swap(arr,start,i);
fullSort(list, arr, start + 1, k);
swap(arr,i,start);
}
}
}
public static void swap(int []arr,int i, int j){
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static void main(String []args){
int [][]arr={{10,20},{30,200},{400,50},{30,20}};
int res= twoCitySchedCost(arr);
System.out.println("结果为"+res);
}
}