简体   繁体   English

置换递归C#

[英]Permutation recursion C#

I have this function that call itself to find all the possible combination with the array of int. 我有自己调用此函数以查找与int数组的所有可能组合的函数。 The problem is that the program calculate the first combination and then, when the recursion continues, the List of combination still contains that value and i don't understand why. 问题是程序计算出第一个组合,然后,当递归继续进行时,组合列表仍包含该值,我不明白为什么。

public static void Permutation(List<int> items, int h, List<int> actualCombination)
    {
        if (h == actualCombination.Count)
        {
            results[results.Count] = actualCombination;
        }
        else
        {
            for (int i = 0; i < items.Count; i++)
            {
                actualCombination.Add(items[i]);

                List<int> temp = new List<int>(items);
                temp.Remove(items[i]);

                Permutation(temp, h, actualCombination);

            }
            return;
        }
    }

after that, i call the function in main. 之后,我在main中调用该函数。 In my case the second parameter specify the combination length."Results" is a Dictionary composed by int as key and List as value that is used to save all the combination. 在我的情况下,第二个参数指定组合长度。“结果”是由int作为键和List作为值组成的Dictionary,用于保存所有组合。

static void Main(string[] args)
    {

        Permutation(new List<int> { 1, 2, 3 }, 3, new List<int>());



        Console.ReadKey();
    }

我通过复制函数添加之前的List解决了该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM