数组的交叉组合算法,求帮助!
有数组:
string[] a = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k" };
要让它最后的组合成像:
a b;a c;a d;...
a b a;a b c;a b d;...
a c a;a c b;a c d;...
让数组内的每一个都相互组合,从两个一组开始,到数组长度一组。然后输出。
求高人帮忙啊!
[最优解释]
static void Main(string[] args)
{
List<string> list = new List<string>() { "a", "b", "c" };
bind(list, new List<string>(), 1);
Console.ReadLine();
}
private static void bind(List<string> list, List<string> source, int count)
{
if (source.Count <= count)
{
if (source.Count > 1)
Write(source);
}
for (int i = 0; i < list.Count; i++)
{
if (source.Contains(list[i].Trim()))
continue;
source.Add(list[i]);
bind(list, source, count + 1);
source.Remove(list[i]);
}
}
private static void Write(List<string> List)
{
for (int i = 0; i < List.Count; i++)
{
Console.Write(List[i]);
}
Console.Write("\n");
}
[其他解释]
string[] a = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k" };
List<string> list = new List<string>();
string str = "";
for (int i = 0; i < a.Length; i++)
{
str = str + a[i];
for (int j = 0; j < a.Length; j++)
{
if (j != i)
{
string temp = str + a[j];
list.Add(temp);
}
}
}
[其他解释]
有人没?
[其他解释]
貌似要3个for循环。。。
[其他解释]
a可以和a组合?
[其他解释]
循环貌似不行。
[其他解释]
可以出现a b a;a c a;
但不能有a a b;b b c;
很纠结啊~
[其他解释]
从你的例子中,我没看出规律,不如你就弄5个长度的数组把所有组合都写出来看看
[其他解释]
比如说;数组是{a,b,c}。那最后就要组合成:
ab;ac;ba;bc;ca;cb;abc;acb;bac;bca;cba;cab;
[其他解释]
不对啊,最后只能输出a开头的,而且最后还输出了12个数的了。
[其他解释]
我还以为你就要a开头- -,那就外头再套个循环。。改改不就行了吗。。
[其他解释]
不行。仔细看了你的需求。我这种还是不行。。。。
看下面的大牛了。。学习一下
[其他解释]
static List<string> sum;
static void Main(string[] args)
{
sum = new List<string>();
List<string> list = new List<string>() { "a", "b", "c" };
bind(list, new List<string>(), 1);
foreach (string s in sum.Where(t => t.Trim() != "").OrderBy(t => t.Length))
Console.Write(s);
Console.ReadLine();
}
private static void bind(List<string> list, List<string> source, int count)
{
if (source.Count <= count)
{
if (source.Count > 1)
Write(source);
}
for (int i = 0; i < list.Count; i++)
{
if (source.Contains(list[i].Trim()))
continue;
source.Add(list[i]);
bind(list, source, count + 1);
source.Remove(list[i]);
}
}
private static void Write(List<string> List)
{
string str = "";
for (int i = 0; i < List.Count; i++)
{
str += List[i];
}
str += "\n";
sum.Add(str);
}
[其他解释]
这个可以,但是就是我的数组里的数据比较多,大概有10个左右,一运行就挂掉了,就一直在运行,就是不显示结果。还能在优化吗?谢谢了!
[其他解释]
高手啊,排列组合问题吧。
[其他解释]
这个可以,已经差不多解决了,谢谢!
[其他解释]
差不多了,结贴了。