C# 笛卡尔积

时间:2023-03-09 17:43:06
C# 笛卡尔积
 void Main()
{
string[] str1 = { "a", "b" };
string[] str2 = { "" };
string[] str3 = { "一", "二", "三" };
string[] str4 = { "", "", "" };
string[] str5 = { "", ""};
string[] str6 = { "", "+", "-" };
List<string[]> list = new List<string[]>();
list.Add(str1);
list.Add(str2);
list.Add(str3);
list.Add(str4);
list.Add(str5);
list.Add(str6);
List<string> result = new List<string>();
Descartes(list, , result, string.Empty);
foreach (var item in result)
{
Console.WriteLine(item);
} } // Define other methods and classes here
private static void Descartes(List<string[]> list, int count, List<string> result, string data)
{ // 获取当前数组
string [] curr=list[count];
foreach(var item in curr)
{
if(count+< list.Count)
{
// 跳至下一层
Descartes(list,count+, result, data+item);
}
else
{
// 达到最底层时将拼接的值存入结果列表中
result.Add(data+item);
}
} }

代码二: 思路一致 , 在最后一层输出结果,其他层递归至下一层

 //定义一个全局二维锯齿数组,数据自己想办法往里填吧
int[ ][ ] IntList=new int[N][ ];
for(int i=;i<N;i++)
{
IntList[i]=new int[M[i]];
} //定义一个一维数组存放结果
int[ ] ResultList=new int[N]; void GetNextResult(int step,int MaxStep)
{
for(int i=;i<IntList[step].Length;i++)
{
ResultList[step]=IntList[step][i];
if(step==MaxStep)
{
//输出ResultList
}
else
{
GetNextResult(step+,MaxStep);
}
}
}