forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1439.go
39 lines (35 loc) · 728 Bytes
/
1439.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var m, n int
func kthSmallest(mat [][]int, k int) int {
m, n = len(mat), len(mat[0])
l, r, res := m, m * 5000, -1
for l < r {
mid := (l + r + 1) >> 1
cnt := dfs(mat, 0, mid, 0, k)
if cnt >= k {
res, r = mid, mid - 1
} else {
l = mid
}
}
return res
}
func dfs(mat [][]int, cur, target, r, k int) int {
if cur > target {
return 0
}
if r == m {
return 1
}
res := 0
for c := 0; c < n; c++ {
cnt := dfs(mat, cur + mat[r][c], target, r + 1, k - res)
if cnt == 0 {
break
}
res += cnt
if res > k {
break
}
}
return res
}