3437. Permutations III 🔒
题目描述
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
解法
方法一:回溯
我们设计一个函数 $\textit{dfs}(i)$,表示当前要填第 $i$ 个位置的数,位置编号从 $0$ 开始。
在 $\textit{dfs}(i)$ 中,如果 $i \geq n$,说明所有位置都已经填完,将当前排列加入答案数组中。
否则,我们枚举当前位置可以填的数 $j$,如果 $j$ 没有被使用过,并且 $j$ 和当前排列的最后一个数不同奇偶性,我们就可以将 $j$ 放在当前位置,继续递归填下一个位置。
时间复杂度 $O(n \times n!)$,空间复杂度 $O(n)$。其中 $n$ 为排列的长度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|