Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 0c2bf1e

Browse files
authoredJan 10, 2021
Create construct-the-lexicographically-largest-valid-sequence.py
1 parent dc2fd0b commit 0c2bf1e

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
 
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Time: O(n!)
2+
# Space: O(n)
3+
4+
class Solution(object):
5+
def constructDistancedSequence(self, n):
6+
"""
7+
:type n: int
8+
:rtype: List[int]
9+
"""
10+
def backtracking(n, i, s, lookup):
11+
if i == len(s):
12+
return True
13+
if s[i]:
14+
return backtracking(n, i+1, s, lookup)
15+
for x in reversed(xrange(1, n+1)):
16+
j = i if x == 1 else i+x
17+
if lookup[x] or j >= len(s) or s[j]:
18+
continue
19+
s[i], s[j], lookup[x] = x, x, True
20+
if backtracking(n, i+1, s, lookup):
21+
return True
22+
s[i], s[j], lookup[x] = 0, 0, False
23+
return False
24+
25+
s, lookup = [0]*(2*n-1), [False]*(n+1)
26+
backtracking(n, 0, s, lookup)
27+
return s

0 commit comments

Comments
 (0)
Please sign in to comment.