我想计算可以使我等于设定值的不同类型的天数。
例如,如果某人有30天年假作为工作的一部分,我想计算一下他们可以选择哪种不同类型的假期。
一个例子是:
5、10、5、2、2、1、5
如您所见,以上等于30。
计算的想法是让准员工知道他们可以休多少天的假。
返回的值也可以是:
10、10、10
这意味着我需要计算等于年假总数的数字组合。
挑战可以用任何编程语言来完成!
我尝试了以下方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
// find all possible combinations of this list
var input = new[] { "1", "2", "3", "4", "5", "6","7","8","9","10","11","12","13","14" };
var output = FastPowerSet(input);
Print(output);
Console.ReadLine();
}
static T[][] FastPowerSet<T>(T[] seq)
{
var powerSet = new T[1 << seq.Length][];
powerSet[0] = new T[0]; // starting only with empty set
for (var i = 0; i < seq.Length; i++)
{
var cur = seq[i];
var count = 1 << i; // doubling list each time
for (var j = 0; j < count; j++)
{
var source = powerSet[j];
var destination = powerSet[count + j] = new T[source.Length + 1];
for (var q = 0; q < source.Length; q++)
destination[q] = source[q];
destination[source.Length] = cur;
}
}
return powerSet;
}
static void Print<T>(T[][] seq)
{
for (var i = 0; i < seq.Length; i++)
{
var line = new StringBuilder();
for (var j = 0; j < seq[i].Length; j++)
{
line.AppendFormat("{0}, ", seq[i][j]);
}
Console.WriteLine(line);
}
}
}
}
谢谢PriceCheaperton!
这里回答了一个更广泛的问题,其中也可以给出给定总和的各部分的大小的限制。
在上面链接的顶部的Python解决方案中,您将像这样修改对函数的调用以解决您的特定示例(我不知道15..30是否有效,否则您需要以与我相同的方式完成列表已经开始):
subset_sum([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15..30],30)
最好的问候,垫子
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句