Recursive Function
Question :
给出sum、min、max和n四个正整数,请输出所有将sum拆分为n个正整数之和,其中每个正整数k都满足:min <= k <= max。这n个正整数之间可以重复,不过由于加法交换率的作用,1 + 2和2 + 1便算是重复的拆分了。
例如,sum = 5,n = 3,min = 1,max = 3,这时候满足条件的拆分方式只有两种:
* 1 + 1 + 3
* 1 + 2 + 2
My Answer:
class Program
{
static int[] array = null;
static void Main(string[] args)
{
Calculate(7, 3, 2, 3);
}
static void Calculate(int sum, int num, int min, int max)
{
if (array == null)
{
array = new int[num];
}
if (num == 1)
{
if (sum == min || sum == max)
{
if (sum == min)
array[0] = min;
if (sum == max)
array[0] = max;
PrintResult();
}
return;
}
for (int i = max; i >= min; i--)
{
array[num - 1] = i;
Calculate(sum - i, num - 1, min, i);
}
}
private static void PrintResult()
{
for (int i = 0; i < array.Length; i++)
{
if (i == array.Length-1)
{
Console.Write(array[i].ToString()+"\n");
}
else
{
Console.Write(array[i].ToString() + "+");
}
}
}
}
0 Comments:
Post a Comment
<< Home