Construct the Lexicographically Largest Valid Sequence LeetCode solution in Python
1class Solution:2def constructDistancedSequence(self, n: int) -> List[int]:3self.ans = None45def dfs(path, used, i):6self.steps += 17if i == len(path):8self.ans = path[:]9return True10if path[i] != 0:11return dfs(path, used, i + 1)12my_ans = [0]13for x in range(n, 0, -1):14if x in used:15continue16if x == 1:17path[i] = x18used.add(1)1920if dfs(path, used, i + 1):21return True2223path[i] = 024used.remove(1)25if i + x < len(path) and path[i + x] == 0:26path[i + x] = path[i] = x27used.add(x)2829if dfs(path, used, i + 1):30return True3132path[i + x] = path[i] = 033used.remove(x)3435return False3637dfs([0] * (1 + 2 * (n - 1)), set(), 0)3839return self.ans