本帖最后由 jerryxjr1220 于 2019-10-30 13:33 编辑
提供一个思路“广度优先搜索策略”,因为有上限限制,所以其实广度并不需要全列举,超过上限的就剪枝,速度还是非常快的:
假如表A = [a,b,c,d] 上限是U
建立一个字典cans = {},把A中的所有项都放进去,键是值的和。
然后依次从表A中取出每一个放入字典中去求和,看是否超过上限,没超就加上,超过就舍弃,循环一遍就出来了。
我手头没有python,用aardio临时写了一下
- import console;
- console.open();
- limit = 5000;
- A = "828,125,740,724,983,321,773,678,841,842,875,377,674,144,340,467,625,916,463,922,255,662,692,123,778,766,254,559,480,483,904,60,305,966,872,935,626,691,832,998,508,657,215,162,858,179,869,674,452,158,520,138,847,452,764,995,600,568,92,496,533,404,186,345,304,420,181,73,547,281,374,376,454,438,553,929,140,298,451,674,91,531,685,862,446,262,477,573,627,624,814,103,294,388"
- A = string.split(A,",");
- list = {}
- cans = {}
- for _,i in A{
- n = tonumber(i);
- table.push(list,n);
- cans[n] = {n}
- }
- for _,ea in list {
- for ei,ec in cans {
- if ei == ea continue ;
- if table.find(ec,ea) continue ;
- if ea+ei>limit continue ;
- new = table.clone(ec);
- table.push(new,ea);
- cans[ea+ei] = new;
- }
- }
- s = ""
- for k,v in cans{
- //console.log(k);
- //console.log(table.unpack(v));
- s ++= tostring(k) ++ '\r\n';
- for _,i in v {
- s ++= tostring(i) ++ '\t';
- }
- s ++= '\r\n';
- }
- console.log(s)
- string.save("temp.txt", s)
- console.pause(true);
复制代码
结果:
5000
144 138 92 547 281 438 553 674 531 685 814 103
|