【发布时间】:2013-01-12 14:40:56
【问题描述】:
给定一个数组,比如 nums = { 1,2,5,3,6,-1,-2,10,11,12},使用最大元素数(比如 maxNums=3) 找到总和(比如 sum =10)= K 的元素
所以如果要使用的 maxNums = 3 求和 = 10 答案是
{1 3 6}
{1 -1 10}
{1 -2 11}
{2 5 3}
{2 -2 10}
{5 6 -1}
{-1 11}
{-2 12}
{10}
我写了一个递归函数来完成这项工作。 如何在没有递归的情况下做到这一点? 和/或内存更少?
class Program
{
static Int32[] nums = { 1,2,5,3,6,-1,-2,10,11,12};
static Int32 sum = 10;
static Int32 maxNums = 3;
static void Main(string[] args)
{
Int32[] arr = new Int32[nums.Length];
CurrentSum(0, 0, 0, arr);
Console.ReadLine();
}
public static void Print(Int32[] arr)
{
for (Int32 i = 0; i < arr.Length; i++)
{
if (arr[i] != 0)
Console.Write(" " +arr[i]);
}
Console.WriteLine();
}
public static void CurrentSum(Int32 sumSoFar, Int32 numsUsed, Int32 startIndex, Int32[] selectedNums)
{
if ( startIndex >= nums.Length || numsUsed > maxNums)
{
if (sumSoFar == sum && numsUsed <= maxNums)
{
Print(selectedNums);
}
return;
}
**//Include the next number and check the sum**
selectedNums[startIndex] = nums[startIndex];
CurrentSum(sumSoFar + nums[startIndex], numsUsed+1, startIndex+1, selectedNums);
**//Dont include the next number**
selectedNums[startIndex] = 0;
CurrentSum(sumSoFar , numsUsed , startIndex + 1, selectedNums);
}
}
【问题讨论】:
-
问题不清楚,你使用的语言也不清楚
-
我使用 C# 作为语言
-
这是子集和问题;这是一个非常著名的问题。有大量关于如何解决它的文献,尽管重要的是要注意在其最一般的形式中它不能快速解决。(也就是说,有一个快速解决方案当且仅当 P= =NP,而且 P 几乎可以肯定不等于 NP。)
-
数组内元素的最小和最大可能值是多少?
-
您不关心运行时间而只想摆脱递归?在这种情况下,我会给你一个提示。考虑堆栈中存储的内容。将其拉出并放入数组中。观察你的递归不会比 maxNums 级别更深。
标签: c# algorithm data-structures recursion