【问题标题】:What is the most efficient way to get all combinations? [duplicate]获得所有组合的最有效方法是什么? [复制]
【发布时间】:2011-10-10 11:24:46
【问题描述】:

可能重复:
Finding all possible combinations of numbers to reach a given sum

问题

您有一个人员列表作为输入,每个人都有一些学分。您将获得一个必须通过使用一个或多个个人学分才能达到的总数。该函数应输出将产生总数的所有组合。

例如见下图:-

static void Main(string[] args)
{
    int total = Convert.ToInt32(args[0]);
    var persons = new List<Person>();
    persons.Add(new Person { Credits = 10, Name="Steve"});
    persons.Add(new Person { Credits = 5, Name = "Paul" });
    persons.Add(new Person { Credits = 4, Name = "David" });
    persons.Add(new Person { Credits = 1, Name = "Kenneth" });

    PrintAllCombinations(persons, total); // The function in question
}
public class Person
{
    public string Name { get; set; }
    public int Credits { get; set; }
}

在上面的例子中,总共有 10 个,PrintAllCombinations 函数应该输出类似于:-

  • 组合 1) 史蒂夫:10
  • 组合 2) 保罗:5,大卫 4,肯尼斯 1
  • 组合 3) 史蒂夫:9,保罗 1
  • 组合 4) 史蒂夫:5,保罗 5
  • ...等

更新:我忘了提,您可以使用个人信用的任何部分

我使用的示例进行了简化,但实际情况将限制为不超过 100 人,并且总数将始终少于 90。

什么是最好的解决方案?

【问题讨论】:

  • 这个问题是c#特有的
  • 我根本看不出这个问题是如何特定于 C# 的。您只需要通用数据结构和一些动态编程。

标签: algorithm


【解决方案1】:

您可以在PythonJavaHaskell 中阅读此普遍问题的解决方案

Finding all possible combinations of numbers to reach a given sum


根据您的编辑指定您可能会获得部分学分,您还应该查看此帖子:

generate a list of combinations/sets of numbers with limited supplies

My solution,用 C 语言编写,同样适用于您的情况。

【讨论】:

    【解决方案2】:

    由于背包问题是 NP 完全问题,因此在一般情况下没有有效的算法。不过由于学分少,可以使用动态规划来记忆如下函数:

    F(N, W) := can we add up to W, using only the first N people?
    
    F(0, 0) = True
    F(0, _) = False
    F(N, W) = F(N-1, W) || F(N-1, W-w[N])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      • 2011-08-14
      • 1970-01-01
      相关资源
      最近更新 更多