日期:2014-05-18 浏览次数:20954 次
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var lst = new int[] { 1, 1, 2, 2, 4, 4, 1, 3, 2 };
foreach (var result in Solve(lst, 5))
{
result.ToList().ForEach(x => { Console.Write("{0} ", x); });
Console.WriteLine();
}
Console.ReadKey();
}
static IEnumerable<IEnumerable<int>> Solve(int[] lst, int sum)
{
foreach (var r in lst.Where(x => x == sum))
yield return new int[] { r };
if (lst.Length > 1)
foreach (var r in Solve(lst.Where((x, index) => index > 0).ToArray(), sum - lst[0]))
yield return new int[] { lst[0] }.Concat(r);
}
}
}
------解决方案--------------------
针对你的“特殊情况”那好写得很。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] data = { 1, 1, 2, 2, 4, 4, 1, 3, 2 };
int n = 5;
var list = data.OrderByDescending(x => x).Select(x => new { g = -1, v = x }).ToList();
int g1 = 0;
while (list.Any(x => x.g == -1))
{
int t = 0;
g1 = list.Max(x => x.g) + 1;
while (t != n)
{
var i = list.Where(x => x.g == -1 && x.v <= n - t).First();
t += i.v;
list.Add(new { g = g1, v = i.v });
list.Remove(i);
}
}
foreach (var i in list.GroupBy(x => x.g).Select(x => string.Join(",", x.Select(y => y.v))))
{
Console.WriteLine(i);
}
}
}
}
------解决方案--------------------
你们代码都是大量的循环。。。
程序这么实现是最差劲的。。。
无语
Int[] s=[1,1,2,2,4,4,1,3,2] 要和等于5 分析下。最少要二个数相加,最多四个数相加。
定义一个新的int[] newS 让int[]的元素之和等于5可以限制newS的元素个数减少循环
------解决方案--------------------
可以用0-1背包问题来解决