Talentd
FleetCode

3437. Permutations III

Medium86.2% acceptance1 companyPremium elsewhere, free here

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

Asked at 1 company

Hints open one at a time

Hint 1
Use backtracking to generate permutations of the first n positive integers while ensuring that each added number alternates between odd and even.
Still stuck?Read the written solution.
Open solution

Similar problems

Permutations IVHard
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
4
Input
2
Input
3
Your code is saved on this device.Solution