Files
hello-algo/en/codes/csharp/chapter_backtracking/permutations_ii.cs
Yudong Jin 2778a6f9c7 Translate all code to English (#1836)
* Review the EN heading format.

* Fix pythontutor headings.

* Fix pythontutor headings.

* bug fixes

* Fix headings in **/summary.md

* Revisit the CN-to-EN translation for Python code using Claude-4.5

* Revisit the CN-to-EN translation for Java code using Claude-4.5

* Revisit the CN-to-EN translation for Cpp code using Claude-4.5.

* Fix the dictionary.

* Fix cpp code translation for the multipart strings.

* Translate Go code to English.

* Update workflows to test EN code.

* Add EN translation for C.

* Add EN translation for CSharp.

* Add EN translation for Swift.

* Trigger the CI check.

* Revert.

* Update en/hash_map.md

* Add the EN version of Dart code.

* Add the EN version of Kotlin code.

* Add missing code files.

* Add the EN version of JavaScript code.

* Add the EN version of TypeScript code.

* Fix the workflows.

* Add the EN version of Ruby code.

* Add the EN version of Rust code.

* Update the CI check for the English version  code.

* Update Python CI check.

* Fix cmakelists for en/C code.

* Fix Ruby comments
2025-12-31 07:44:52 +08:00

56 lines
1.9 KiB
C#

/**
* File: permutations_ii.cs
* Created Time: 2023-04-24
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_backtracking;
public class permutations_ii {
/* Backtracking algorithm: Permutations II */
void Backtrack(List<int> state, int[] choices, bool[] selected, List<List<int>> res) {
// When the state length equals the number of elements, record the solution
if (state.Count == choices.Length) {
res.Add(new List<int>(state));
return;
}
// Traverse all choices
HashSet<int> duplicated = [];
for (int i = 0; i < choices.Length; i++) {
int choice = choices[i];
// Pruning: do not allow repeated selection of elements and do not allow repeated selection of equal elements
if (!selected[i] && !duplicated.Contains(choice)) {
// Attempt: make choice, update state
duplicated.Add(choice); // Record the selected element value
selected[i] = true;
state.Add(choice);
// Proceed to the next round of selection
Backtrack(state, choices, selected, res);
// Backtrack: undo choice, restore to previous state
selected[i] = false;
state.RemoveAt(state.Count - 1);
}
}
}
/* Permutations II */
List<List<int>> PermutationsII(int[] nums) {
List<List<int>> res = [];
Backtrack([], nums, new bool[nums.Length], res);
return res;
}
[Test]
public void Test() {
int[] nums = [1, 2, 2];
List<List<int>> res = PermutationsII(nums);
Console.WriteLine("Input array nums = " + string.Join(", ", nums));
Console.WriteLine("All permutations res = ");
foreach (List<int> permutation in res) {
PrintUtil.PrintList(permutation);
}
}
}