列出一个字符串的全排列
在一些数学问题里面可能会用到, 使用递归做的,也许不算最好,仅作参考:
using System;
using System.Collections.Generic;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//我们做一个最简单的排列组合,求出字符串的全排列.
char[] arr_char = new char[] { 'A', 'B', 'C', 'D','E' };
string[] result = get_all_position(null,arr_char,arr_char.Length);
Console.WriteLine(string.Join(",",result));
Console.WriteLine("元素个数: " + result.Length.ToString() + " 个");
Console.ReadLine();
}
static string[] get_all_position(string[] all_position, char[] arr_char, int level)
{
string[] base_position = null;
if (level == 0)
return new string[] { arr_char[0].ToString() };
else
base_position = get_all_position(all_position, arr_char, level - 1);
if (level == arr_char.Length)
return base_position;
char new_char = arr_char[level];
int string_length = 0;
if (base_position.Length > 0)
string_length = base_position[0].Length;
string[] new_position = new string[base_position.Length * (level+1)];
for (int i = 0; i < base_position.Length; i++)
{
new_position[(string_length+1) * i] = new_char + base_position[i];
for (int k = 0; k < string_length; k++)
{
new_position[(string_length+1) * i + k + 1] = base_position[i][k] + base_position[i].Replace(base_position[i][k], new_char);
}
}
return new_position;
}
}
}
using System.Collections.Generic;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//我们做一个最简单的排列组合,求出字符串的全排列.
char[] arr_char = new char[] { 'A', 'B', 'C', 'D','E' };
string[] result = get_all_position(null,arr_char,arr_char.Length);
Console.WriteLine(string.Join(",",result));
Console.WriteLine("元素个数: " + result.Length.ToString() + " 个");
Console.ReadLine();
}
static string[] get_all_position(string[] all_position, char[] arr_char, int level)
{
string[] base_position = null;
if (level == 0)
return new string[] { arr_char[0].ToString() };
else
base_position = get_all_position(all_position, arr_char, level - 1);
if (level == arr_char.Length)
return base_position;
char new_char = arr_char[level];
int string_length = 0;
if (base_position.Length > 0)
string_length = base_position[0].Length;
string[] new_position = new string[base_position.Length * (level+1)];
for (int i = 0; i < base_position.Length; i++)
{
new_position[(string_length+1) * i] = new_char + base_position[i];
for (int k = 0; k < string_length; k++)
{
new_position[(string_length+1) * i + k + 1] = base_position[i][k] + base_position[i].Replace(base_position[i][k], new_char);
}
}
return new_position;
}
}
}