如何通过使用 C# 语言进行回溯法,找出字符串的所有排列?
找到第一个位置的字符并用第一个字符交换其余字符。比如在 ABC 中,在第一次迭代中,通过用 A 分别与 A、B 和 C 交换,形成了三个字符串:ABC、BAC 和 CBA。对其余字符重复步骤,例如固定第二个字符 B,依此类推。现在再次进行交换以返回到前一个位置。在 ABC 中,我们通过再次固定 B 形成 ABC,并且我们回溯到前一个位置并将 B 与 C 交换。因此,现在我们得到 ABC 和 ACB。
示例
using System;
namespace ConsoleApplication{
public class BackTracking{
public void StringPermutation(string word, int start, int end){
if (start == end){
Console.WriteLine(word);
}
else{
for (int i = start; i <= end; i++){
Swap(ref word, start, i);
StringPermutation(word, start + 1, end);
Swap(ref word, start, i);
}
}
}
private void Swap(ref string word, int start, int end){
char[] arr = word.ToCharArray();
char temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
word = new string(arr);
}
}
class Program{
static void Main(string[] args){
BackTracking b = new BackTracking();
b.StringPermutation("ABC", 0, 2);
}
}
}输出
ABC ACB BAC BCA CBA CAB
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP