题目地址:
https://www.lintcode.com/problem/order-allocation/description
给定一个正整数二维矩阵 A A A,要求从 A A A的每一行取一个数,取的数不能在同一列,使得总和最大。返回每行取的数的下标。
思路是DFS。直接暴力枚举所有情况即可。递归的时候记录路径,递归到最深层的时候算一下总分是否更大,如果更大则更新答案。代码如下:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
// 记录最大总分
private int max;
/**
* @param score: When the j-th driver gets the i-th order, we can get score[i][j] points.
* @return: return an array that means the array[i]-th driver gets the i-th order.
*/
public int[] orderAllocation(int[][] score) {
// write your code here
int n = score.length;
int[] res = new int[n];
dfs(0, 0, score, new boolean[n], new ArrayList<>(), res);
return res;
}
private void dfs(int n, int sum, int[][] score, boolean[] visited, List<Integer> list, int[] res) {
if (n == score.length) {
// 发现了更优解,更新答案
if (sum > max) {
max = sum;
for (int i = 0; i < res.length; i++) {
res[i] = list.get(i);
}
}
return;
}
for (int i = 0; i < score[0].length; i++) {
if (!visited[i]) {
visited[i] = true;
list.add(i);
dfs(n + 1, sum + score[n][i], score, visited, list, res);
list.remove(list.size() - 1);
visited[i] = false;
}
}
}
}
时间复杂度 O ( n ! ) O(n!) O(n!),空间 O ( n ) O(n) O(n)。