|
| 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(object): |
| 5 | + def minimumTimeRequired(self, jobs, k): |
| 6 | + """ |
| 7 | + :type jobs: List[int] |
| 8 | + :type k: int |
| 9 | + :rtype: int |
| 10 | + """ |
| 11 | + def backtracking(jobs, i, cap, counts): |
| 12 | + if i == len(jobs): |
| 13 | + return True |
| 14 | + for j in xrange(len(counts)): |
| 15 | + if counts[j]+jobs[i] <= cap: |
| 16 | + counts[j] += jobs[i] |
| 17 | + if backtracking(jobs, i+1, cap, counts): |
| 18 | + return True |
| 19 | + counts[j] -= jobs[i] |
| 20 | + if counts[j] == 0: |
| 21 | + break |
| 22 | + return False |
| 23 | + |
| 24 | + jobs.sort(reverse=True) |
| 25 | + left, right = max(jobs), sum(jobs) |
| 26 | + while left <= right: |
| 27 | + mid = left + (right-left)//2 |
| 28 | + if backtracking(jobs, 0, mid, [0]*k): |
| 29 | + right = mid-1 |
| 30 | + else: |
| 31 | + left = mid+1 |
| 32 | + return left |
| 33 | + |
| 34 | + |
| 35 | +# Time: O(k * k^n), the real complexity shoud be less, but hard to analyze |
| 36 | +# Space: O(n + k) |
| 37 | +class Solution2(object): |
| 38 | + def minimumTimeRequired(self, jobs, k): |
| 39 | + """ |
| 40 | + :type jobs: List[int] |
| 41 | + :type k: int |
| 42 | + :rtype: int |
| 43 | + """ |
| 44 | + def backtracking(jobs, i, counts, result): |
| 45 | + if i == len(jobs): |
| 46 | + result[0] = min(result[0], max(counts)) |
| 47 | + return |
| 48 | + for j in xrange(len(counts)): |
| 49 | + if counts[j]+jobs[i] <= result[0]: |
| 50 | + counts[j] += jobs[i] |
| 51 | + backtracking(jobs, i+1, counts, result) |
| 52 | + counts[j] -= jobs[i] |
| 53 | + if counts[j] == 0: |
| 54 | + break |
| 55 | + |
| 56 | + jobs.sort(reverse=False) |
| 57 | + result = [sum(jobs)] |
| 58 | + backtracking(jobs, 0, [0]*k, result) |
| 59 | + return result[0] |
0 commit comments