【问题标题】:Permutation recursion C#排列递归 C#
【发布时间】:2017-08-31 07:26:32
【问题描述】:

我有这个函数,它调用自身来查找与 int 数组的所有可能组合。问题是程序计算了第一个组合,然后,当递归继续时,组合列表仍然包含该值,我不明白为什么。

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;
        }
    }

之后,我在 main 中调用该函数。在我的例子中,第二个参数指定组合长度。“结果”是一个字典,由 int 作为键和 List 作为值组成,用于保存所有组合。

static void Main(string[] args)
    {

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



        Console.ReadKey();
    }

【问题讨论】:

  • Eric Lippert 有一篇关于 Producing permutations 的不错的博客
  • 什么是results
  • Tim Rogers 结果是我用来保存所有组合的函数之外的字典

标签: c# recursion permutation


【解决方案1】:

我通过复制函数 add 之前的 List 解决了这个问题。

【讨论】:

  • 太棒了;那么请关闭问题:接受您的回答,删除原始内容,或您认为对以后搜索此网站的人有用的任何内容。
  • 是的,我明天会接受我的答案,因为我现在不能接受,它说我需要等待大约两天才能接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
  • 2011-07-23
  • 2012-10-18
  • 2016-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多