Skip to content

Commit

Permalink
Update 1439.Find-the-Kth-Smallest-Sum-of-a-Matrix-With-Sorted-Rows_v3…
Browse files Browse the repository at this point in the history
….cpp
  • Loading branch information
wisdompeak authored Jun 18, 2021
1 parent 28faa74 commit 15f64ac
Showing 1 changed file with 24 additions and 20 deletions.
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
typedef pair<int,vector<int>> PIV;
class Solution {
class Solution {
public:
int kthSmallest(vector<vector<int>>& mat, int k)
{
int left = 0, right = INT_MAX;
while (left < right)
{
int target = left + (right-left)/2;
if (checkOK(mat, target, k))
int target = left+(right-left)/2;
if (checkOK(mat, target, k)) // If the # of arrays whose sum <= target is at least k
right = target;
else
left = target + 1;
left = target+1;
}
return left;
}

// If the # of arrays whose sum <= target is at least k
return left;
}

// Check if the # of arrays whose sum <= target is at least k
// o(K)
bool checkOK(vector<vector<int>>& mat, int target, int k)
{
int m = mat.size();
Expand All @@ -24,29 +24,33 @@ class Solution {
int sum = 0;
for (int i=0; i<m; i++)
sum += mat[i][0];
int count = 1;

if (sum > target) return false;

int count = 1;
dfs(mat, 0, sum, target, count, k);
dfs(mat, 0, sum, count, target, k);

return (count >= k);
return count>=k;
}

void dfs(vector<vector<int>>& mat, int row, int sum, int target, int& count, int k)
void dfs(vector<vector<int>>& mat, int row, int sum, int& count, int target, int k)
{
int m = mat.size();
int n = mat[0].size();

if (count >= k) return;
if (row == m) return;

for (int j = 0; j<n; j++)
if (row==m) return;
for (int j=0; j<n; j++)
{
if (sum + mat[row][j] - mat[row][0] <= target)
{
if (j>0) count++;
dfs(mat, row+1, sum + mat[row][j] - mat[row][0], target, count, k);
dfs(mat, row+1, sum + mat[row][j] - mat[row][0], count, target, k);
}
else
break;
}
}
}
};

0 comments on commit 15f64ac

Please sign in to comment.