【leetcode C++】1439. 有序矩阵中的第 k 个最小数组和 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows

1439. 有序矩阵中的第 k 个最小数组和
1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows

在这里插入图片描述

class Solution {
public:
    int kthSmallest(vector<vector<int>>& mat, int k) {
        priority_queue<pair<int, vector<int> > > PQ;  // 优先队列,用来存放sum及其路径
        set<vector<int> > S;  // 路径的集合,防止重复
        int sum = 0, result = 0;
        vector<int> path;  // 当前路径
        for(int ii = 0; ii < mat.size(); ii++) {  // 初始化
            sum += mat[ii][0];
            path.push_back(0);
        }
        PQ.push({-sum, path});  // 对sum取相反数,用大顶堆来模拟小顶堆
        for(int cnt = 0; cnt < k; cnt++) {
            auto A = PQ.top();  // 取出第 cnt 个最小值
            PQ.pop();
            result = -A.first;
            path = A.second;
            for(int ii = 0; ii < path.size(); ii++) {  // 放入下一次所有可能的最小值到优先队列中
                if(path[ii] + 1 >= mat[ii].size()) continue;  // 这里注意,路径下标不能超过当前数组大小
                path[ii]++;
                if(S.find(path) == S.end()) {
                    sum = 0;
                    for(int jj = 0; jj < path.size(); jj++) {
                        sum += mat[jj][path[jj]];
                    }
                    PQ.push({-sum, path});
                    S.insert(path);
                }
                path[ii]--;
            }
        }
        return result;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值