forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
kth-smallest-instructions.py
33 lines (31 loc) · 1.04 KB
/
kth-smallest-instructions.py
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
# Time: O((m + n)^2)
# Space: O(1)
class Solution(object):
def kthSmallestPath(self, destination, k):
"""
:type destination: List[int]
:type k: int
:rtype: str
"""
def nCr(n, r): # Time: O(n), Space: O(1)
if n < r:
return 0
if n-r < r:
return nCr(n, n-r)
c = 1
for k in xrange(1, r+1):
c *= n-k+1
c //= k
return c
r, c = destination
result = []
while r+c:
count = nCr(r+(c-1), r) # the number of HX..X combinations
if k <= count: # the kth instruction is one of HX..X combinations, so go right
c -= 1
result.append('H')
else: # the kth instruction is one of VX..X combinations, so go down
k -= count # the kth one of XX..X combinations is the (k-count)th one of VX..X combinations
r -= 1
result.append('V')
return "".join(result)