.net 重复组合算法(从集合中提取N个数,得到所有组合:单个数值可重复)

算法很简答,就是迭代计算,得到所有组合就行了,废话不多说,直接上代码(看起来复杂,实现起来代码其实很简单)

/// <summary>
/// 从dataList中提取n个数,得到所有组合(数字可重复)
/// </summary>
/// <param name="dataList">数据集合</param>
/// <param name="n">提取数字数量</param>
/// <param name="value">默认为null,迭代时使用</param>
/// <returns></returns>
 private static List<List<int>> GetCombinations(List<int> dataList, int n, List<int> value = null)
{
    List<List<int>> result = new List<List<int>>();
    for (int i = 0, count = dataList.Count; i < count; i++)
    {
        List<int> itemList = new List<int>();
        if (value != null && value.Count > 0)
        {
            itemList.AddRange(value);
        }
        itemList.Add(dataList[i]);

        if (itemList.Count == n)
        {
            result.Add(itemList);
        }
        else
        {
            result.AddRange(GetCombinations(dataList, n, itemList));
        }
    }
    return result;
}

static void Main(string[] args)
{
    List<int> IntArr = new List<int>() { 1, 2, 3, 4, 5 }; //整型数组
    List<List<int>> ListCombination = GetCombinations(IntArr, 3); //从中提取3个数,返回所有组合
    foreach (List<int> arr in ListCombination)
    {
        foreach (int item in arr)
        {
            Console.Write(item + " ");
        }
        Console.WriteLine("");
    }
    Console.ReadKey();
}

  

posted @ 2020-08-14 17:00  安然亦智  阅读(646)  评论(0编辑  收藏  举报