【发布时间】:2017-06-04 15:37:42
【问题描述】:
我有一个简单的数学问题。 这是一个数组。
数组 = { 1, 2, 3 }
需要上述数组元素的所有可能组合,使总和 = 5。
解:{ 1, 1, 1, 1, 1 } { 1, 1, 1, 2 } { 1, 2, 2 } { 2, 3 } { 1, 1, 3 }
注意:只要总和为 5,您可以使用任意数组元素任意次数。
int weight = 5;
List<int> weights = new List<int>() { 1, 2 ,3};
void function1(int weight,List<int> weights, List<List<int>> combinationlist)
{
for (int i = 0; i < weights.Count; i++)
{
if (weight % weights[i] == 0)
{
int num = weight / weights[i];
List<int> mylist = new List<int>();
for (int j = 0; j < num; j++)
{
mylist.Add(weights[i]);
}
if (!combinationlist.Contains(mylist))
combinationlist.Add(mylist);
}
}
}
现在上面的函数生成了{1,1,1,1,1}解的简单组合。
void function2(int weight, List<int> weights, List<List<int>> combinationlist)
{
int i = weights.Count - 1;
Stack<int> mystack = new Stack<int>();
List<int> combinationarray = new List<int>();
foreach (var x in weights)
mystack.Push(x);
for (;i >= 0; i--)
{
if (weight <= weights[i])
mystack.Pop();
}
int remainder = 0;
if (weight % mystack.Peek() != 0)
remainder = weight % mystack.Peek();
int quotient = weight / mystack.Peek();
combine(combinationlist,combinationarray,mystack,quotient,remainder);
}
组合功能
void combine(List<List<int>>combinations,List<int>combination,Stack<int> mystack,int quotient, int remweight)
{
for (int i = 0; i < quotient; i++)
{
combination.Add(mystack.Peek());
}
if (remweight > 1)
remweight = remweight - mystack.Peek() * quotient;
else if (remweight == 0)
{
if (!combinations.Contains(combination))
combinations.Add(combination);
return;
}
else
return;
while (mystack.Peek() > remweight )
{
if (mystack.Count != 0)
mystack.Pop();
}
quotient = remweight / mystack.Peek();
combine(combinations, combination, mystack, quotient, remweight);
}
所有这些工作。我只能得到两个解决方案 {2,1,1,1} {1,1,1,1,1}。
【问题讨论】:
-
你试过什么?你得到什么错误?所以不是来做你的功课的:)
-
你有没有尝试解决这个问题?到目前为止,您做了哪些考虑?我们在这里不仅仅是为您解决问题,展示您的努力以及您出错的地方,我们将帮助您走上正确的轨道
-
更大问题的一部分。我努力了。没有得到所有可能的答案。
-
请展示您的尝试,以便我们知道您在问题上的立场。
-
为什么这被标记为“动态规划”?是否明确要求动态编程?输入中的所有数字都可以假设为正吗?是否允许 0?
标签: algorithm recursion dynamic-programming