diff --git a/solution/3400-3499/3437.Permutations III/README.md b/solution/3400-3499/3437.Permutations III/README.md new file mode 100644 index 0000000000000..5af5d96409539 --- /dev/null +++ b/solution/3400-3499/3437.Permutations III/README.md @@ -0,0 +1,215 @@ +--- +comments: true +difficulty: 中等 +edit_url: https://github.com/doocs/leetcode/edit/main/solution/3400-3499/3437.Permutations%20III/README.md +--- + + + +# [3437. Permutations III 🔒](https://leetcode.cn/problems/permutations-iii) + +[English Version](/solution/3400-3499/3437.Permutations%20III/README_EN.md) + +## 题目描述 + + + +

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:

+ + + + + +## 解法 + + + +### 方法一:回溯 + +我们设计一个函数 $\textit{dfs}(i)$,表示当前要填第 $i$ 个位置的数,位置编号从 $0$ 开始。 + +在 $\textit{dfs}(i)$ 中,如果 $i \geq n$,说明所有位置都已经填完,将当前排列加入答案数组中。 + +否则,我们枚举当前位置可以填的数 $j$,如果 $j$ 没有被使用过,并且 $j$ 和当前排列的最后一个数不同奇偶性,我们就可以将 $j$ 放在当前位置,继续递归填下一个位置。 + +时间复杂度 $O(n \times n!)$,空间复杂度 $O(n)$。其中 $n$ 为排列的长度。 + + + +#### Python3 + +```python +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 +``` + +#### Java + +```java +class Solution { + private List ans = new ArrayList<>(); + private boolean[] vis; + private int[] t; + private int n; + + public int[][] permute(int n) { + this.n = n; + t = new int[n]; + vis = new boolean[n + 1]; + dfs(0); + return ans.toArray(new int[0][]); + } + + private void dfs(int i) { + if (i >= n) { + ans.add(t.clone()); + return; + } + for (int j = 1; j <= n; ++j) { + if (!vis[j] && (i == 0 || t[i - 1] % 2 != j % 2)) { + vis[j] = true; + t[i] = j; + dfs(i + 1); + vis[j] = false; + } + } + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + vector> permute(int n) { + vector> ans; + vector vis(n); + vector t; + auto dfs = [&](this auto&& dfs, int i) -> void { + if (i >= n) { + ans.push_back(t); + return; + } + for (int j = 1; j <= n; ++j) { + if (!vis[j] && (i == 0 || t[i - 1] % 2 != j % 2)) { + vis[j] = true; + t.push_back(j); + dfs(i + 1); + t.pop_back(); + vis[j] = false; + } + } + }; + dfs(0); + return ans; + } +}; +``` + +#### Go + +```go +func permute(n int) (ans [][]int) { + vis := make([]bool, n+1) + t := make([]int, n) + var dfs func(i int) + dfs = func(i int) { + if i >= n { + ans = append(ans, slices.Clone(t)) + return + } + for j := 1; j <= n; j++ { + if !vis[j] && (i == 0 || t[i-1]%2 != j%2) { + vis[j] = true + t[i] = j + dfs(i + 1) + vis[j] = false + } + } + } + dfs(0) + return +} +``` + +#### TypeScript + +```ts +function permute(n: number): number[][] { + const ans: number[][] = []; + const vis: boolean[] = Array(n).fill(false); + const t: number[] = Array(n).fill(0); + const dfs = (i: number) => { + if (i >= n) { + ans.push([...t]); + return; + } + for (let j = 1; j <= n; ++j) { + if (!vis[j] && (i === 0 || t[i - 1] % 2 !== j % 2)) { + vis[j] = true; + t[i] = j; + dfs(i + 1); + vis[j] = false; + } + } + }; + dfs(0); + return ans; +} +``` + + + + + + diff --git a/solution/3400-3499/3437.Permutations III/README_EN.md b/solution/3400-3499/3437.Permutations III/README_EN.md new file mode 100644 index 0000000000000..42e4d07147b1d --- /dev/null +++ b/solution/3400-3499/3437.Permutations III/README_EN.md @@ -0,0 +1,215 @@ +--- +comments: true +difficulty: Medium +edit_url: https://github.com/doocs/leetcode/edit/main/solution/3400-3499/3437.Permutations%20III/README_EN.md +--- + + + +# [3437. Permutations III 🔒](https://leetcode.com/problems/permutations-iii) + +[中文文档](/solution/3400-3499/3437.Permutations%20III/README.md) + +## Description + + + +

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
  • +
+ + + +## Solutions + + + +### Solution 1: Backtracking + +We design a function $\textit{dfs}(i)$, which represents filling the $i$-th position, with position indices starting from $0$. + +In $\textit{dfs}(i)$, if $i \geq n$, it means all positions have been filled, and we add the current permutation to the answer array. + +Otherwise, we enumerate the numbers $j$ that can be placed in the current position. If $j$ has not been used and $j$ has a different parity from the last number in the current permutation, we can place $j$ in the current position and continue to recursively fill the next position. + +The time complexity is $O(n \times n!)$, and the space complexity is $O(n)$. Here, $n$ is the length of the permutation. + + + +#### Python3 + +```python +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 +``` + +#### Java + +```java +class Solution { + private List ans = new ArrayList<>(); + private boolean[] vis; + private int[] t; + private int n; + + public int[][] permute(int n) { + this.n = n; + t = new int[n]; + vis = new boolean[n + 1]; + dfs(0); + return ans.toArray(new int[0][]); + } + + private void dfs(int i) { + if (i >= n) { + ans.add(t.clone()); + return; + } + for (int j = 1; j <= n; ++j) { + if (!vis[j] && (i == 0 || t[i - 1] % 2 != j % 2)) { + vis[j] = true; + t[i] = j; + dfs(i + 1); + vis[j] = false; + } + } + } +} +``` + +#### C++ + +```cpp +class Solution { +public: + vector> permute(int n) { + vector> ans; + vector vis(n); + vector t; + auto dfs = [&](this auto&& dfs, int i) -> void { + if (i >= n) { + ans.push_back(t); + return; + } + for (int j = 1; j <= n; ++j) { + if (!vis[j] && (i == 0 || t[i - 1] % 2 != j % 2)) { + vis[j] = true; + t.push_back(j); + dfs(i + 1); + t.pop_back(); + vis[j] = false; + } + } + }; + dfs(0); + return ans; + } +}; +``` + +#### Go + +```go +func permute(n int) (ans [][]int) { + vis := make([]bool, n+1) + t := make([]int, n) + var dfs func(i int) + dfs = func(i int) { + if i >= n { + ans = append(ans, slices.Clone(t)) + return + } + for j := 1; j <= n; j++ { + if !vis[j] && (i == 0 || t[i-1]%2 != j%2) { + vis[j] = true + t[i] = j + dfs(i + 1) + vis[j] = false + } + } + } + dfs(0) + return +} +``` + +#### TypeScript + +```ts +function permute(n: number): number[][] { + const ans: number[][] = []; + const vis: boolean[] = Array(n).fill(false); + const t: number[] = Array(n).fill(0); + const dfs = (i: number) => { + if (i >= n) { + ans.push([...t]); + return; + } + for (let j = 1; j <= n; ++j) { + if (!vis[j] && (i === 0 || t[i - 1] % 2 !== j % 2)) { + vis[j] = true; + t[i] = j; + dfs(i + 1); + vis[j] = false; + } + } + }; + dfs(0); + return ans; +} +``` + + + + + + diff --git a/solution/3400-3499/3437.Permutations III/Solution.cpp b/solution/3400-3499/3437.Permutations III/Solution.cpp new file mode 100644 index 0000000000000..e48a629101950 --- /dev/null +++ b/solution/3400-3499/3437.Permutations III/Solution.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + vector> permute(int n) { + vector> ans; + vector vis(n); + vector t; + auto dfs = [&](this auto&& dfs, int i) -> void { + if (i >= n) { + ans.push_back(t); + return; + } + for (int j = 1; j <= n; ++j) { + if (!vis[j] && (i == 0 || t[i - 1] % 2 != j % 2)) { + vis[j] = true; + t.push_back(j); + dfs(i + 1); + t.pop_back(); + vis[j] = false; + } + } + }; + dfs(0); + return ans; + } +}; diff --git a/solution/3400-3499/3437.Permutations III/Solution.go b/solution/3400-3499/3437.Permutations III/Solution.go new file mode 100644 index 0000000000000..39844a45ef432 --- /dev/null +++ b/solution/3400-3499/3437.Permutations III/Solution.go @@ -0,0 +1,21 @@ +func permute(n int) (ans [][]int) { + vis := make([]bool, n+1) + t := make([]int, n) + var dfs func(i int) + dfs = func(i int) { + if i >= n { + ans = append(ans, slices.Clone(t)) + return + } + for j := 1; j <= n; j++ { + if !vis[j] && (i == 0 || t[i-1]%2 != j%2) { + vis[j] = true + t[i] = j + dfs(i + 1) + vis[j] = false + } + } + } + dfs(0) + return +} diff --git a/solution/3400-3499/3437.Permutations III/Solution.java b/solution/3400-3499/3437.Permutations III/Solution.java new file mode 100644 index 0000000000000..197f8b2cc2d78 --- /dev/null +++ b/solution/3400-3499/3437.Permutations III/Solution.java @@ -0,0 +1,29 @@ +class Solution { + private List ans = new ArrayList<>(); + private boolean[] vis; + private int[] t; + private int n; + + public int[][] permute(int n) { + this.n = n; + t = new int[n]; + vis = new boolean[n + 1]; + dfs(0); + return ans.toArray(new int[0][]); + } + + private void dfs(int i) { + if (i >= n) { + ans.add(t.clone()); + return; + } + for (int j = 1; j <= n; ++j) { + if (!vis[j] && (i == 0 || t[i - 1] % 2 != j % 2)) { + vis[j] = true; + t[i] = j; + dfs(i + 1); + vis[j] = false; + } + } + } +} diff --git a/solution/3400-3499/3437.Permutations III/Solution.py b/solution/3400-3499/3437.Permutations III/Solution.py new file mode 100644 index 0000000000000..13524abb93ceb --- /dev/null +++ b/solution/3400-3499/3437.Permutations III/Solution.py @@ -0,0 +1,19 @@ +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 diff --git a/solution/3400-3499/3437.Permutations III/Solution.ts b/solution/3400-3499/3437.Permutations III/Solution.ts new file mode 100644 index 0000000000000..78a21d189c357 --- /dev/null +++ b/solution/3400-3499/3437.Permutations III/Solution.ts @@ -0,0 +1,21 @@ +function permute(n: number): number[][] { + const ans: number[][] = []; + const vis: boolean[] = Array(n).fill(false); + const t: number[] = Array(n).fill(0); + const dfs = (i: number) => { + if (i >= n) { + ans.push([...t]); + return; + } + for (let j = 1; j <= n; ++j) { + if (!vis[j] && (i === 0 || t[i - 1] % 2 !== j % 2)) { + vis[j] = true; + t[i] = j; + dfs(i + 1); + vis[j] = false; + } + } + }; + dfs(0); + return ans; +} diff --git a/solution/README.md b/solution/README.md index b6486d2e050a7..240270edc914e 100644 --- a/solution/README.md +++ b/solution/README.md @@ -3447,6 +3447,7 @@ | 3434 | [子数组操作后的最大频率](/solution/3400-3499/3434.Maximum%20Frequency%20After%20Subarray%20Operation/README.md) | `贪心`,`数组`,`哈希表`,`动态规划`,`前缀和` | 中等 | 第 434 场周赛 | | 3435 | [最短公共超序列的字母出现频率](/solution/3400-3499/3435.Frequencies%20of%20Shortest%20Supersequences/README.md) | `位运算`,`图`,`拓扑排序`,`数组`,`字符串`,`枚举` | 困难 | 第 434 场周赛 | | 3436 | [Find Valid Emails](/solution/3400-3499/3436.Find%20Valid%20Emails/README.md) | | 简单 | | +| 3437 | [Permutations III](/solution/3400-3499/3437.Permutations%20III/README.md) | | 中等 | 🔒 | ## 版权 diff --git a/solution/README_EN.md b/solution/README_EN.md index e978b9a0dfc8e..89acd17266bf4 100644 --- a/solution/README_EN.md +++ b/solution/README_EN.md @@ -3445,6 +3445,7 @@ Press Control + F(or Command + F on | 3434 | [Maximum Frequency After Subarray Operation](/solution/3400-3499/3434.Maximum%20Frequency%20After%20Subarray%20Operation/README_EN.md) | `Greedy`,`Array`,`Hash Table`,`Dynamic Programming`,`Prefix Sum` | Medium | Weekly Contest 434 | | 3435 | [Frequencies of Shortest Supersequences](/solution/3400-3499/3435.Frequencies%20of%20Shortest%20Supersequences/README_EN.md) | `Bit Manipulation`,`Graph`,`Topological Sort`,`Array`,`String`,`Enumeration` | Hard | Weekly Contest 434 | | 3436 | [Find Valid Emails](/solution/3400-3499/3436.Find%20Valid%20Emails/README_EN.md) | | Easy | | +| 3437 | [Permutations III](/solution/3400-3499/3437.Permutations%20III/README_EN.md) | | Medium | 🔒 | ## Copyright