tuiwucarrer/Admin.NET/Admin.NET.Core/Util/UtilGetPermutations.cs

41 lines
941 B
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Admin.NET.Core;
public class UtilGetPermutations
{
public static HashSet<string> GetPermutations(string str)
{
var results = new HashSet<string>();
Permute(str.ToCharArray(), 0, results);
return results;
}
public static void Permute(char[] chars, int index, HashSet<string> results)
{
if (index == chars.Length)
{
results.Add(new string(chars));
return;
}
for (int i = index; i < chars.Length; i++)
{
Swap(chars, index, i);
Permute(chars, index + 1, results);
Swap(chars, index, i); // 还原
}
}
public static void Swap(char[] chars, int i, int j)
{
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}