楼上的速度很快,递归用的也相当漂亮,瑕疵就是没有考虑到乱序的情况。
我这一串代码你可以试一下
static void Main(string[] args)
{
Console.WriteLine("************************");
{
string[] strArr = { "a", "b", "c", "d" };
OperateStr(strArr);
}
Console.WriteLine("");
Console.WriteLine("************************");
Console.ReadKey();
}
///
///
///
///
static void OperateStr(string[] arr)
{
ListstrList = new List ();//定义一个字符串列表,存储组合的字符
//组合成abcd需要循环3次即length-1次
for (int i = 0; i < arr.Length - 1; i++)
{
if (strList != null && strList.Count > 0)
{
strList.AddRange(BindStrArr(strList.ToArray(), arr));//用拼接出的新数组和原数组继续拼接出多一个字符长度的字符串数组,继续存储在strList中
}
else
{
strList.AddRange(BindStrArr(arr, arr));//第一次用原数组和原数组拼接出两个字符长度的新数组,并存储在strList中
}
}
foreach (var str in strList)
{
Console.Write(string.Format("{0},", str));
}
}
///
/// 两个数组里的元素进行组合,含有相同元素的跳过
///
///
///
///
static string[] BindStrArr(string[] arr1, string[] arr2)
{
ListstrList = new List ();
string[] arr3;
foreach (string tmp1 in arr1)
{
foreach (string tmp2 in arr2)
{
if (tmp1.Contains(tmp2))
continue;
strList.Add(string.Format("{0}{1}", tmp1, tmp2));
}
}
arr3 = strList.ToArray();
return arr3;
}
static void Main(string[] args)
{
Listarr = new List () { "A", "B", "C" ,"D","E"};
Listret = new List ();
Fun(arr, ret);
Console.Write(string.Join("\n", ret.ToArray()));
Console.ReadLine();
}
static void Fun(Listarr, List ret, int len = 2)
{
int[] index = new int[len];
for (int i = 0; i < index.Length; i++)
{
index[i] = i;
}
bool ok;
do
{
while (index[len - 1] < arr.Count)
{
string s = "";
for (int i = 0; i < len; i++)
s += arr[index[i]];
ret.Add(s);
index[len - 1]++;
}
ok = true;
for (int i = len - 2; i >= 0; i--)
{
if (index[i] < arr.Count - (len - i))
{
index[i]++;
ok = false;
for (int j = i + 1; j < len; j++)
{
index[j] = index[j - 1] + 1;
}
break;
}
}
} while (ok == false);
if (len < arr.Count)
Fun(arr, ret, len + 1);
}
可以的