doutangdan3588 2015-09-17 11:45
浏览 70

复杂性/ PHP - 数组内任何整数组合等于另一个整数

I am really bad in math and complexity calculations so I would like to ask you for help.

I need to write a function which takes an array of integers and another integer and returns true if any combination of integers inside the array (sum) equals to the another integer and false otherwise.

The best result I was able to achieve is O(n!) - Pretty newbie performance...

Could you please help me write such a function in a more efficient way? Or at least give me a hint.

  • 写回答

1条回答 默认 最新

  • dt3358 2015-09-17 12:37
    关注

    I think you could do it in that way

    1. if(sum(intgers)) < another integer return false
    2. Take first integer
    3. current = first
    4. foreach (number in left integers)
    5. result = current + number
    6. if result = another integer return true
    7. if result > another integer end this tree
    8. else current = result
    9. to step 3 with new data. And so on with recursion.

    In fact it can give you bruteforce, it have dependency on data. Example (1,2,3,4,5,6,7,8,9,10) and integer to check is 1000. But you can check it in the first step. (added as step 0)

    But checking that result is already not available will drop a lot of variants in the beginning of search.

    I am sure it s not best, but not very hard to implement and it usually helps great with calculation. Hope it is understandable.

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向