求助取N个,等于固定值算法.

czyoooo 2011-10-12 08:11:21
ID TOTAL
1 100
2 200
3 200
4 300
5 400
6 500


取其中几个累加等于1000,的所有ID
例如:
100+200+200+500=1000, 得到1,2,3,6
200+300+500=1000,得到2,4,6或3,4,6
100+400+500=1000,得到1,5,6
......



求这样的函数.

...全文
111 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
jshi123 2011-10-12
  • 打赏
  • 举报
回复

static void Main(string[] args)
{
int[] values = { 100, 200, 200, 300, 400, 500 };
var testdata = values.Select((n, i) => new { id = i + 1, total = n }).ToArray();
var total = 1000;

Func<IEnumerable<int[]>, int[], IEnumerable<int[]>> comb = (x, y) =>
from a in x
from b in y
where a.Count() == 0 || a.Last() < b
select a.Concat(new[] { b }).ToArray();

var indices = Enumerable.Range(0, testdata.Length).ToArray();
var list = new int[][] { new int[] { } }.AsEnumerable();
var result = Enumerable.Range(1, testdata.Length)
.SelectMany(i => list = comb(list, indices))
.Where(c => c.Sum(i => testdata[i].total) == total)
.Select(c => c.Select(i => testdata[i]));

foreach (var c in result)
Console.WriteLine("({0})\t {1} = {2}",
string.Join(", ", c.Select(d => d.id)),
string.Join(" + ", c.Select(d => d.total)),
total);
}
chenchenyangll 2011-10-12
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 czyoooo 的回复:]

这样的写法2的N次方.内存能够?
如果记录数量为200.恐怖呀.
[/Quote]

用背包
czyoooo 2011-10-12
  • 打赏
  • 举报
回复
这样的写法2的N次方.内存能够?
如果记录数量为200.恐怖呀.
threenewbee 2011-10-12
  • 打赏
  • 举报
回复
懒得专门为你这个写算法了。。。

给你一个排列组合再筛选的的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>() { 100, 200, 300, 400, 500, 600 };
list.Combo(1, list.Count)
.Where(x => x.Sum() == 1000).ToList().ForEach(x => Console.WriteLine(String.Join("", x)) );
}
}

static class ListCombo
{
public static IEnumerable<List<T>> Combo<T>(this List<T> sourcelist, int min, int max)
{
for (int i = min; i <= max; i++)
foreach (var item in _Combo(sourcelist, i))
yield return item;
}

static IEnumerable<List<T>> _Combo<T>(this List<T> sourcelist, int len)
{
if (len <= 0)
{
yield return new List<T>();
}
else
{
int[] pos = new int[len];
for (int i = 0; i < len; i++) pos[i] = i;
while (pos[0] < sourcelist.Count - len)
{
List<T> newlist = new List<T>();
for (int i = 0; i < len; i++) newlist.Add(sourcelist[pos[i]]);
for (int i = len - 1; i >= 0; i--)
{
if (pos[i] < sourcelist.Count - len + i)
{
pos[i]++;
for (int j = i + 1; j <= len - 1; j++)
pos[j] = pos[i] + j - i;
break;
}
else
{
continue;
}
}
yield return newlist;
}
List<T> last = new List<T>();
for (int i = sourcelist.Count - len; i < sourcelist.Count; i++)
last.Add(sourcelist[i]);
yield return last;
}
}
}
}
czyoooo 2011-10-12
  • 打赏
  • 举报
回复
都是C++的,C#的有吗?
vrhero 2011-10-12
  • 打赏
  • 举报
回复
子集合加总问题...贪婪算法,动态规划,自己google去...

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧