<p>You are given an <code>m x n</code> matrix <code>mat</code> that has its rows sorted in non-decreasing order and an integer <code>k</code>.</p>

<p>You are allowed to choose <strong>exactly one element</strong> from each row to form an array.</p>

<p>Return <em>the </em><code>k<sup>th</sup></code><em> smallest array sum among all possible arrays</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> mat = [[1,3,11],[2,4,6]], k = 5
<strong>Output:</strong> 7
<strong>Explanation:</strong> Choosing one element from each row, the first k smallest sum are:
[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> mat = [[1,3,11],[2,4,6]], k = 9
<strong>Output:</strong> 17
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7
<strong>Output:</strong> 9
<strong>Explanation:</strong> Choosing one element from each row, the first k smallest sum are:
[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9.  
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m == mat.length</code></li>
	<li><code>n == mat.length[i]</code></li>
	<li><code>1 &lt;= m, n &lt;= 40</code></li>
	<li><code>1 &lt;= mat[i][j] &lt;= 5000</code></li>
	<li><code>1 &lt;= k &lt;= min(200, n<sup>m</sup>)</code></li>
	<li><code>mat[i]</code> is a non-decreasing array.</li>
</ul>

class Solution:
    def kthSmallest(self, mat: List[List[int]], k: int) -> int:
        def check(s: int) -> bool:
            left_k = k
            # 返回是否找到 k 个子数组和
            def dfs(i: int, s: int) -> bool:
                if i < 0:  # 能递归到这里，说明数组和不超过二分的 s
                    nonlocal left_k
                    left_k -= 1
                    return left_k == 0  # 是否找到 k 个
                for x in mat[i]:  # 「枚举选哪个」，注意 mat[i] 是有序的
                    if x - mat[i][0] > s:  # 选 x 不选 mat[i][0]
                        break  # 剪枝：后面的元素更大，无需枚举
                    if dfs(i - 1, s - (x - mat[i][0])):  # 选 x 不选 mat[i][0]
                        return True  # 找到 k 个就一直返回 True，不再递归
                return False
            return dfs(len(mat) - 1, s - sl)  # 先把第一列的所有数都选上

        sl = sum(row[0] for row in mat)
        sr = sum(row[-1] for row in mat)
        return sl + bisect_left(range(sl, sr), True, key=check)



# 时间复杂度：O(mklogmin(n,k))，其中 m 和 n 分别为 mat 的行数和列数。每次循环相当于解决一遍第 373 题，时间为 O(klogmin(n,k))，所以总的时间复杂度为 O(mklogmin(n,k))。
# 空间复杂度：O(min(n,k))。堆中至多有 O(min(n,k)) 个元素。




        
        



85