An algorithm to determine a subset sequence in O(n)?

烈酒焚心 提交于 2019-12-13 09:28:40

问题


How can i aproach this problem by induction?

Suppose that you are given an algorithm as a black box you cannot see how it is designed it has the following properties: if you input any sequence of real numbers and an integer k, the algorithm will answer YES or NO indicating whether there is a subset of numbers whose sum is exactly k. Show how to use this black box to find the subset of a given sequence {X1, …., Xn} whose sum is k. You can use the black box O(n) times.

Any idea?


回答1:


I'm not entirely convinced that induction is necessary here.

Here's my two cents:

Suppose you have a sequence of numbers S, and integer k, and you already know that there exists a subset of numbers whose sum is k. Now, remove a number from your sequence (call it i), and use your black box on what remains (using the same k as before).

  • If the algorithm returns YES on the new sequence, what does that tell you about i and any subset of S whose sum is k?
  • If the algorithm returns NO on the new sequence, what does that tell you about i and any subset of S whose sum is k?


来源:https://stackoverflow.com/questions/18749371/an-algorithm-to-determine-a-subset-sequence-in-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!