-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathpermutations-iv.py
58 lines (55 loc) · 1.56 KB
/
permutations-iv.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# Time: O(n^2)
# Space: O(n)
# combinatorics
class Solution(object):
def permute(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[int]
"""
result = []
cnt = [1]*n
for i in xrange(len(cnt)-1):
cnt[i+1] = min(cnt[i]*((i+2)//2), k)
lookup = [False]*n
for i in xrange(n):
for j in xrange(n):
if not (not lookup[j] and ((i == 0 and n%2 == 0) or (j+1)%2 == (1 if not result else (result[-1]%2)^1))):
continue
if k <= cnt[n-1-i]:
break
k -= cnt[n-1-i]
else:
return []
lookup[j] = True
result.append(j+1)
return result
# Time: O(n^2)
# Space: O(n)
# combinatorics
class Solution2(object):
def permute(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[int]
"""
result = []
fact = [1]*(((n-1)+1)//2+1)
for i in xrange(len(fact)-1):
fact[i+1] = fact[i]*(i+1)
lookup = [False]*n
for i in xrange(n):
cnt = fact[(n-1-i)//2]*fact[((n-1-i)+1)//2]
for j in xrange(n):
if not (not lookup[j] and ((i == 0 and n%2 == 0) or (j+1)%2 == (1 if not result else (result[-1]%2)^1))):
continue
if k <= cnt:
break
k -= cnt
else:
return []
lookup[j] = True
result.append(j+1)
return result