笛卡爾積求二維數組所有組合


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