笛卡尔积求二维数组所有组合


static void Main(string[] args)
{
    List<List<string>> allList = new List<List<string>>
    {
        new List<string>{ "a","b","c"},
        new List<string>{ "1","2","3"},
        new List<string>{ "A","B","C","D","E"}
    };
    List<string> result = new List<string>();
    Fun(allList, 0, result, string.Empty);
    foreach (var item in result)
    {
        Console.Write(item + "_");
    }
}

/// <param name="list">二维数组</param>
/// <param name="count">二维数组的索引</param>
/// <param name="result">返回的结果集</param>
/// <param name="str">单个组合</param>
public static void Fun(List<List<string>> list, int count, List<string> result, string str)
{
    //获取当前数组
    List<string> current = list[count];
    foreach (var item in current)
    {
        if (count + 1 < list.Count)
        {
            //跳至下一个数组
            Fun(list, count + 1, result, str + item);
        }
        else
        {
            //到达最后一个数组,将拼接的单个组合添加到结果集
            result.Add(str + item);
        }
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM