【Lintcode】1909. Order Allocation

题目地址:

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值