|
| 1 | +// Time: O(k^n * logr), the real complexity shoud be much less, but hard to analyze |
| 2 | +// Space: O(n + k) |
| 3 | + |
| 4 | +class Solution { |
| 5 | +public: |
| 6 | + int minimumTimeRequired(vector<int>& jobs, int k) { |
| 7 | + sort(begin(jobs), end(jobs), greater<int>()); |
| 8 | + int left = *max_element(cbegin(jobs), cend(jobs)); |
| 9 | + int right = accumulate(cbegin(jobs), cend(jobs), 0); |
| 10 | + while (left <= right) { |
| 11 | + const auto& mid = left + (right - left) / 2; |
| 12 | + vector<int> counts(k); |
| 13 | + if (backtracking(jobs, 0, mid, &counts)) { |
| 14 | + right = mid - 1; |
| 15 | + } else { |
| 16 | + left = mid + 1; |
| 17 | + } |
| 18 | + } |
| 19 | + return left; |
| 20 | + } |
| 21 | + |
| 22 | +private: |
| 23 | + bool backtracking(const vector<int>& jobs, |
| 24 | + int i, int cap, |
| 25 | + vector<int> *counts) { |
| 26 | + if (i == size(jobs)) { |
| 27 | + return true; |
| 28 | + } |
| 29 | + for (int j = 0; j < size(*counts); ++j) { |
| 30 | + if ((*counts)[j] + jobs[i] <= cap) { |
| 31 | + (*counts)[j] += jobs[i]; |
| 32 | + if (backtracking(jobs, i + 1, cap, counts)) { |
| 33 | + return true; |
| 34 | + } |
| 35 | + (*counts)[j] -= jobs[i]; |
| 36 | + } |
| 37 | + if ((*counts)[j] == 0) { |
| 38 | + break; |
| 39 | + } |
| 40 | + } |
| 41 | + return false; |
| 42 | + } |
| 43 | +}; |
| 44 | + |
| 45 | +// Time: O(k^n), the real complexity shoud be less, but hard to analyze |
| 46 | +// Space: O(n + k) |
| 47 | +class Solution2 { |
| 48 | +public: |
| 49 | + int minimumTimeRequired(vector<int>& jobs, int k) { |
| 50 | + sort(begin(jobs), end(jobs), greater<int>()); |
| 51 | + int result = accumulate(cbegin(jobs), cend(jobs), 0); |
| 52 | + vector<int> counts(k); |
| 53 | + backtracking(jobs, 0, &counts, &result); |
| 54 | + return result; |
| 55 | + } |
| 56 | + |
| 57 | +private: |
| 58 | + void backtracking(const vector<int>& jobs, |
| 59 | + int i, |
| 60 | + vector<int> *counts, |
| 61 | + int *result) { |
| 62 | + if (i == size(jobs)) { |
| 63 | + *result = min(*result, *max_element(cbegin(*counts), cend(*counts))); |
| 64 | + return; |
| 65 | + } |
| 66 | + for (int j = 0; j < size(*counts); ++j) { |
| 67 | + if ((*counts)[j] + jobs[i] <= *result) { |
| 68 | + (*counts)[j] += jobs[i]; |
| 69 | + backtracking(jobs, i + 1, counts, result); |
| 70 | + (*counts)[j] -= jobs[i]; |
| 71 | + } |
| 72 | + if ((*counts)[j] == 0) { |
| 73 | + break; |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | +}; |
0 commit comments