feat: Add the section of permutations problem. (#476)

* Add the section of permutations problem.

* Update permutations_problem.md
This commit is contained in:
Yudong Jin
2023-04-24 03:33:30 +08:00
committed by GitHub
parent 95ed93dc4b
commit c6eecfd0dc
14 changed files with 462 additions and 0 deletions
@@ -0,0 +1,48 @@
/**
* File: permutations_i.cpp
* Created Time: 2023-04-24
* Author: Krahets (krahets@163.com)
*/
#include "../include/include.hpp"
/* 回溯算法:全排列 I */
void backtrack(vector<int> &state, const vector<int> &choices, vector<bool> &selected, vector<vector<int>> &res) {
// 当状态长度等于元素数量时,记录解
if (state.size() == choices.size()) {
res.push_back(state);
return;
}
// 遍历所有选择
for (int i = 0; i < choices.size(); i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if (!selected[i]) {
// 尝试
selected[i] = true; // 做出选择
state.push_back(choice); // 更新状态
backtrack(state, choices, selected, res);
// 回退
selected[i] = false; // 撤销选择
state.pop_back(); // 恢复到之前的状态
}
}
}
/* Driver Code */
int main() {
vector<int> nums = {1, 2, 3};
// 回溯算法
vector<int> state;
vector<bool> selected(nums.size(), false);
vector<vector<int>> res;
backtrack(state, nums, selected, res);
cout << "输入数组 nums = ";
printVector(nums);
cout << "所有排列 res = ";
printVectorMatrix(res);
return 0;
}
@@ -0,0 +1,50 @@
/**
* File: permutations_ii.cpp
* Created Time: 2023-04-24
* Author: Krahets (krahets@163.com)
*/
#include "../include/include.hpp"
/* 回溯算法:全排列 II */
void backtrack(vector<int> &state, const vector<int> &choices, vector<bool> &selected, vector<vector<int>> &res) {
// 当状态长度等于元素数量时,记录解
if (state.size() == choices.size()) {
res.push_back(state);
return;
}
// 遍历所有选择
unordered_set<int> duplicated;
for (int i = 0; i < choices.size(); i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if (!selected[i] && duplicated.find(choice) == duplicated.end()) {
// 尝试
duplicated.emplace(choice); // 记录选择过的元素值
selected[i] = true; // 做出选择
state.push_back(choice); // 更新状态
backtrack(state, choices, selected, res);
// 回退
selected[i] = false; // 撤销选择
state.pop_back(); // 恢复到之前的状态
}
}
}
/* Driver Code */
int main() {
vector<int> nums = {1, 1, 2};
// 回溯算法
vector<int> state;
vector<bool> selected(nums.size(), false);
vector<vector<int>> res;
backtrack(state, nums, selected, res);
cout << "输入数组 nums = ";
printVector(nums);
cout << "所有排列 res = ";
printVectorMatrix(res);
return 0;
}
@@ -0,0 +1,45 @@
/**
* File: permutations_i.java
* Created Time: 2023-04-24
* Author: Krahets (krahets@163.com)
*/
package chapter_backtracking;
import java.util.*;
public class permutations_i {
/* 回溯算法:全排列 I */
public static void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> res) {
// 当状态长度等于元素数量时,记录解
if (state.size() == choices.length) {
res.add(new ArrayList<Integer>(state));
return;
}
// 遍历所有选择
for (int i = 0; i < choices.length; i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if (!selected[i]) {
// 尝试
selected[i] = true; // 做出选择
state.add(choice); // 更新状态
backtrack(state, choices, selected, res);
// 回退
selected[i] = false; // 撤销选择
state.remove(state.size() - 1); // 恢复到之前的状态
}
}
}
public static void main(String[] args) {
int[] nums = { 1, 2, 3 };
List<List<Integer>> res = new ArrayList<List<Integer>>();
// 回溯算法
backtrack(new ArrayList<Integer>(), nums, new boolean[nums.length], res);
System.out.println("输入数组 nums = " + Arrays.toString(nums));
System.out.println("所有排列 res = " + res);
}
}
@@ -0,0 +1,47 @@
/**
* File: permutations_ii.java
* Created Time: 2023-04-24
* Author: Krahets (krahets@163.com)
*/
package chapter_backtracking;
import java.util.*;
public class permutations_ii {
/* 回溯算法:全排列 II */
public static void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> res) {
// 当状态长度等于元素数量时,记录解
if (state.size() == choices.length) {
res.add(new ArrayList<Integer>(state));
return;
}
// 遍历所有选择
Set<Integer> duplicated = new HashSet<Integer>();
for (int i = 0; i < choices.length; i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if (!selected[i] && !duplicated.contains(choice)) {
// 尝试
duplicated.add(choice); // 记录选择过的元素值
selected[i] = true; // 做出选择
state.add(choice); // 更新状态
backtrack(state, choices, selected, res);
// 回退
selected[i] = false; // 撤销选择
state.remove(state.size() - 1); // 恢复到之前的状态
}
}
}
public static void main(String[] args) {
int[] nums = { 1, 2, 2 };
List<List<Integer>> res = new ArrayList<List<Integer>>();
// 回溯算法
backtrack(new ArrayList<Integer>(), nums, new boolean[nums.length], res);
System.out.println("输入数组 nums = " + Arrays.toString(nums));
System.out.println("所有排列 res = " + res);
}
}
@@ -54,6 +54,9 @@ def traverse(nums: list[int]) -> None:
# 直接遍历数组
for num in nums:
count += 1
# 同时遍历数据索引和元素
for i, num in enumerate(nums):
count += 1
def find(nums: list[int], target: int) -> int:
@@ -0,0 +1,43 @@
"""
File: permutations_i.py
Created Time: 2023-04-15
Author: Krahets (krahets@163.com)
"""
import sys, os.path as osp
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from modules import *
def backtrack(
state: list[int], choices: list[int], selected: list[bool], res: list[list[int]]
):
"""回溯算法:全排列 I"""
# 当状态长度等于元素数量时,记录解
if len(state) == len(choices):
res.append(list(state))
return
# 遍历所有选择
for i, choice in enumerate(choices):
# 剪枝:不允许重复选择元素
if not selected[i]:
# 尝试
selected[i] = True # 做出选择
state.append(choice) # 更新状态
backtrack(state, choices, selected, res)
# 回退
selected[i] = False # 撤销选择
state.pop() # 恢复到之前的状态
"""Driver Code"""
if __name__ == "__main__":
nums = [1, 2, 3]
res = []
# 回溯算法
backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
print(f"输入数组 nums = {nums}")
print(f"所有排列 res = {res}")
@@ -0,0 +1,45 @@
"""
File: permutations_ii.py
Created Time: 2023-04-15
Author: Krahets (krahets@163.com)
"""
import sys, os.path as osp
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from modules import *
def backtrack(
state: list[int], choices: list[int], selected: list[bool], res: list[list[int]]
):
"""回溯算法:全排列 II"""
# 当状态长度等于元素数量时,记录解
if len(state) == len(choices):
res.append(list(state))
return
# 遍历所有选择
duplicated = set[int]()
for i, choice in enumerate(choices):
# 剪枝:不允许重复选择元素 且 不允许重复选择相等元素
if not selected[i] and choice not in duplicated:
# 尝试
duplicated.add(choice) # 记录选择过的元素值
selected[i] = True # 做出选择
state.append(choice) # 更新状态
backtrack(state, choices, selected, res)
# 回退
selected[i] = False # 撤销选择
state.pop() # 恢复到之前的状态
"""Driver Code"""
if __name__ == "__main__":
nums = [1, 2, 2]
res = []
# 回溯算法
backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
print(f"输入数组 nums = {nums}")
print(f"所有排列 res = {res}")