mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-13 09:18:09 +08:00
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
54 lines
1.7 KiB
C#
54 lines
1.7 KiB
C#
/**
|
|
* File: permutations_i.cs
|
|
* Created Time: 2023-04-24
|
|
* Author: hpstory (hpstory1024@163.com)
|
|
*/
|
|
|
|
namespace hello_algo.chapter_backtracking;
|
|
|
|
public class permutations_i {
|
|
/* Backtracking: permutations I */
|
|
void Backtrack(List<int> state, int[] choices, bool[] selected, List<List<int>> res) {
|
|
// Record a solution when the state length equals the number of elements
|
|
if (state.Count == choices.Length) {
|
|
res.Add(new List<int>(state));
|
|
return;
|
|
}
|
|
// Iterate over all choices
|
|
for (int i = 0; i < choices.Length; i++) {
|
|
int choice = choices[i];
|
|
// Prune: do not choose an element more than once
|
|
if (!selected[i]) {
|
|
// Try: make a choice and update the state
|
|
selected[i] = true;
|
|
state.Add(choice);
|
|
// Proceed to the next choice
|
|
Backtrack(state, choices, selected, res);
|
|
// Backtrack: undo the choice and restore the previous state
|
|
selected[i] = false;
|
|
state.RemoveAt(state.Count - 1);
|
|
}
|
|
}
|
|
}
|
|
|
|
/* Permutations I */
|
|
List<List<int>> PermutationsI(int[] nums) {
|
|
List<List<int>> res = [];
|
|
Backtrack([], nums, new bool[nums.Length], res);
|
|
return res;
|
|
}
|
|
|
|
[Test]
|
|
public void Test() {
|
|
int[] nums = [1, 2, 3];
|
|
|
|
List<List<int>> res = PermutationsI(nums);
|
|
|
|
Console.WriteLine("Input array nums = " + string.Join(", ", nums));
|
|
Console.WriteLine("All permutations: res = ");
|
|
foreach (List<int> permutation in res) {
|
|
PrintUtil.PrintList(permutation);
|
|
}
|
|
}
|
|
}
|