求有N个数组成的和为M的情况。
举个简单例子。求3个数字的和等于6的情况
List<int[]> list = new List<int[]>();
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
for (int k = 0; k < 6; k++)
{
if (i + j + k == 6)
{
list.Add(new int[] { i, j, k });
}
}
}
}
现在想做成通用的比如:GetSomeMethord(6,3);
private List<int> GetSomeMethord(int sum, int count)
{
--代码实现过程
return null;
}
还没有想到方法,请给点思路。 --------------------编程问答-------------------- 递归。
类似:http://bbs.csdn.net/topics/390360329 --------------------编程问答--------------------
using System;--------------------编程问答-------------------- 如果你写成 List<int> GetSomeMethord(int sum, int count),那么就算是“挤破脑袋”也难以想出流程来的,因为接口的概念就错了。 --------------------编程问答-------------------- 这个位问题用递归最简洁, --------------------编程问答--------------------
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int count = 0;
foreach (var lst in GetSomething(6, 3))
{
Console.Write("第{0:D2}个解答:", ++count);
foreach (var x in lst)
Console.Write("{0} ", x);
Console.WriteLine();
}
Console.WriteLine("................Press any key");
Console.ReadKey();
}
public static IEnumerable<IEnumerable<int>> GetSomething(int sum, int count)
{
return GetSomething(sum, count, sum);
}
public static IEnumerable<IEnumerable<int>> GetSomething(int sum, int count, int maxNum)
{
if (count < 1)
throw new InvalidOperationException();
else if (sum <= 0)
yield break;
else if (count == 1)
{
if (sum <= maxNum)
yield return new List<int> { sum };
}
else
foreach (var x in from n in Enumerable.Range(1, maxNum)
let sub = GetSomething(sum - n, count - 1, n)
from lst in sub
select lst.Concat(new int[] { n }))
yield return x;
}
}
}
很明显我写错的了,上面都用List<int[]> list = new List<int[]>();
for (int i = 0; i < 6; i++)
太粗心的了。 --------------------编程问答--------------------
还是不类似, 那个是指定的数字,
这个是指定个数,数字不限制。 --------------------编程问答--------------------
看样子以后,得使劲学习Linq。 --------------------编程问答-------------------- 声明 IEnumerable<IEnumerable<int>> GetSomething 这个类型,在下边的递归算法
from n in Enumerable.Range(1, maxNum)
let sub = GetSomething(sum - n, count - 1, n)
from lst in sub
select lst.Concat(new int[] { n }
就具有决定性作用。算法中,你递归计算 count -1 个数字的组合的集合,然后把 n 这个数字分别加入这个集合的每一个结果中。
如果定义为 <IEnumerable<int>类型,那么你就难以反应起“递归”能怎样表达这个算法了。 --------------------编程问答--------------------
思路都是一样的。要是不会举一反三,那给代码有什么意义呢?
补充:.NET技术 , C#