高分求教完整算法代码

苏宁莫 2017-11-08 06:35:46
现在有n(键盘输入)块钱,有水果价目表(苹果:23,梨:35,香蕉:47,西瓜60,哈密瓜:1000,荔枝:339,柚子:550),求可以买多少个水果,有几种结果。要用.net算法实现不能简单的7层循环嵌套
...全文
325 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
peng2739956 2017-11-09
  • 打赏
  • 举报
回复
用递归吧

void Main()
{
	var items = new[] {
		new ItemPrice("苹果", 23),
		new ItemPrice("梨", 35),
		new ItemPrice("香蕉", 47),
		new ItemPrice("哈密瓜", 1000),
		new ItemPrice("荔枝", 339),
		new ItemPrice("柚子", 550),
	};
	
	Array.Sort(items, (a,b)=>b.Price.CompareTo(a.Price));
	int n = Int32.Parse(Console.ReadLine());
	GetCount(n, items).Select(r=>string.Join(", ",r.Zip(items,(a,b)=>new{a,b})
		.Select(item=>(item.b.Title+"x"+item.a)))) .Dump();
}

IEnumerable<int[]> GetCount(int n, ItemPrice[] items) {
	return GetCount(n, items, new int[items.Length], 0);
}

IEnumerable<int[]> GetCount(int n, ItemPrice[] items, int[] count, int i) {
	if (i < items.Length-1 ) {
		for(int c=0; n>=0 ;c++, n-=items[i].Price) {
			count[i] = c;
			foreach(var result in GetCount(n, items, count, i+1))
					yield return result;
		}
	} else {
		count[i] = n / items[i].Price;
		yield return count;
	}
}

struct ItemPrice {
	public ItemPrice(string title, int price) {
		this.Title = title; this.Price = price;
	}
	public string Title;
	public int Price;
}
linqpd 执行就成
苏宁莫 2017-11-09
  • 打赏
  • 举报
回复
背包算法是一个最优解,这里要求的是所有可能性,不一样哈;也别说100元兑换,那是一个整除,没有余数的,也不一样
苏宁莫 2017-11-09
  • 打赏
  • 举报
回复
可以重复买同一种水果,然后剩余的钱买不了更多的一个水果。求的是所有可能性的一个总数
  • 打赏
  • 举报
回复
搜索打包算法……
peng2739956 2017-11-09
  • 打赏
  • 举报
回复
好像不对。 我算的能买多少种 看错了 尴尬
peng2739956 2017-11-09
  • 打赏
  • 举报
回复
随便写个了,按照最多来算

void Main()
{
	double price=double.Parse(Console.ReadLine());
	var arr=new []{23,35,47,60,1000,339,550};
	arr.OrderBy(x=>x).Dump();
	int sum=0;
	int flag=0;
	foreach(int item in arr)
	{
		sum+=item;
		if(sum<=price)
			flag++;
		else
			break;
	}
	flag.Dump();
}
peng2739956 2017-11-09
  • 打赏
  • 举报
回复
题目 不对,是最多买多少个水果还是怎么样
真相重于对错 2017-11-09
  • 打赏
  • 举报
回复
百度搜索动态规划
YUHUI01 2017-11-09
  • 打赏
  • 举报
回复
看都看不懂,唉

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

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