C# 笛卡尔积
1 void Main() 2 { 3 string[] str1 = { "a", "b" }; 4 string[] str2 = { "1" }; 5 string[] str3 = { "一", "二", "三" }; 6 string[] str4 = { "4", "5", "6" }; 7 string[] str5 = { "7", "8"}; 8 string[] str6 = { "9", "+", "-" }; 9 List<string[]> list = new List<string[]>(); 10 list.Add(str1); 11 list.Add(str2); 12 list.Add(str3); 13 list.Add(str4); 14 list.Add(str5); 15 list.Add(str6); 16 List<string> result = new List<string>(); 17 Descartes(list, 0, result, string.Empty); 18 foreach (var item in result) 19 { 20 Console.WriteLine(item); 21 } 22 23 } 24 25 // Define other methods and classes here 26 private static void Descartes(List<string[]> list, int count, List<string> result, string data) 27 { 28 29 // 获取当前数组 30 string [] curr=list[count]; 31 foreach(var item in curr) 32 { 33 if(count+1< list.Count) 34 { 35 // 跳至下一层 36 Descartes(list,count+1, result, data+item); 37 } 38 else 39 { 40 // 达到最底层时将拼接的值存入结果列表中 41 result.Add(data+item); 42 } 43 } 44 45 }
代码二: 思路一致 , 在最后一层输出结果,其他层递归至下一层
1 //定义一个全局二维锯齿数组,数据自己想办法往里填吧 2 int[ ][ ] IntList=new int[N][ ]; 3 for(int i=0;i<N;i++) 4 { 5 IntList[i]=new int[M[i]]; 6 } 7 8 //定义一个一维数组存放结果 9 int[ ] ResultList=new int[N]; 10 11 void GetNextResult(int step,int MaxStep) 12 { 13 for(int i=0;i<IntList[step].Length;i++) 14 { 15 ResultList[step]=IntList[step][i]; 16 if(step==MaxStep) 17 { 18 //输出ResultList 19 } 20 else 21 { 22 GetNextResult(step+1,MaxStep); 23 } 24 } 25 }
本文来自博客园,作者:mushishi,转载请注明原文链接:https://www.cnblogs.com/mushishi/p/3968404.html

浙公网安备 33010602011771号