Problem
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.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= n <= 10
Solution
Intuition
This is the classic permutations problem. We can use backtracking to generate all possible orderings of the numbers 1 to n.
Approach
Use a recursive backtracking function that builds up a permutation by adding unused numbers at each step. When the permutation is complete (length n), add it to the result.
Code
C++
|
|
Go
|
|
Java
|
|
Kotlin
|
|
Python
|
|
Rust
|
|
TypeScript
|
|
Complexity
- ⏰ Time complexity:
O(n!)
(there are n! permutations, each takes O(n) to build) - 🧺 Space complexity:
O(n!)
(for storing all permutations)