Permutations III Problem
#3437
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3437.
Given an integer n, an alternating permutation is a permutation of the first n positive integers such that no two adjacent elements are both odd or both even.
Return all such alternating permutations sorted in lexicographical order.
Example 1:
Input: n = 4
Output: [[1,2,3,4],[1,4,3,2],[2,1,4,3],[2,3,4,1],[3,2,1,4],[3,4,1,2],[4,1,2,3],[4,3,2,1]]
Example 2:
Input: n = 2
Output: [[1,2],[2,1]]
Example 3:
Input: n = 3
Output: [[1,2,3],[3,2,1]]
Constraints:
1 <= n <= 10
Solution
Approach: Backtracking
Fill the positions one by one with dfs(i). When i == n, the current permutation is complete, so save it.
Otherwise try every number j from 1 to n in increasing order (which yields the permutations in lexicographic order). Use j if it is not used yet and, for i > 0, its parity differs from the previous number. Mark it, recurse, then unmark it.
Complexity: O(n * n!) time and O(n) extra space for the recursion.
class Solution:
def permute(self, n: int) -> List[List[int]]:
def dfs(i: int) -> None:
if i >= n:
ans.append(t[:])
return
for j in range(1, n + 1):
if not vis[j] and (i == 0 or t[-1] % 2 != j % 2):
t.append(j)
vis[j] = True
dfs(i + 1)
vis[j] = False
t.pop()
ans = []
t = []
vis = [False] * (n + 1)
dfs(0)
return ans