pong网的算法题,超时了,发到这边帮忙看看怎样

strife013 2013-01-05 02:33:43
/// <summary>
/// 给定一个数t,以及n个整数,在这n个整数中找到相加之和为t的所有组合,例如t = 4,n = 6,这6个数为[4, 3, 2, 2, 1, 1],这样输出就有4个不同的组合,
/// 它们的相加之和为4:4, 3+1, 2+2, and 2+1+1。请设计一个高效算法实现这个需求。
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
int t = 4;
List<int> source = new List<int>();
source.Add(4);
source.Add(3);
source.Add(2);
source.Add(2);
source.Add(1);
source.Add(1);
List<List<int>> result = new List<List<int>>();
source.Sort();
List<List<int>> rs = GetResult(t, source);
List<List<int>> rss = FilterResult(rs);
}

public static Dictionary<string, int> DicKey = new Dictionary<string, int>();
public static List<List<int>> GetResult(int target, List<int> source)
{
List<List<int>> result = new List<List<int>>();
int length = source.Count;
for (int i = length - 1; i >= 0; i--)
{
///从排序的数组中得到
if (source[i] < target)
{
List<List<int>> inResult = GetResult(target - source[i], source.Take(i).ToList());
foreach (List<int> ll in inResult)
{
ll.Add(source[i]);
}
result.AddRange(inResult);
}
else if (source[i] == target)
{

List<int> inr = new List<int>();
inr.Add(source[i]);
result.Add(inr);
}
else
{
List<List<int>> inResult = GetResult(target - source[0], source.Take(i).ToList());
result.AddRange(inResult);
}
}

return result;
}

public static List<List<int>> FilterResult(List<List<int>> source)
{
List<List<int>> rs = new List<List<int>>();
for (int i = source.Count - 1; i >= 0; i--)
{
if (!DicKey.ContainsKey(string.Join(",", source[i])))
{
rs.Add(source[i]);
DicKey.Add(string.Join(",", source[i]), 1);
}
}
return rs;
}
...全文
68 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Assassin_ 2013-01-05
  • 打赏
  • 举报
回复
先顶个。然后研究

110,555

社区成员

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

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

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