note
rubasov
I've just skimmed your code, but if I'm right then your algorithm is lucky to find the correct output for this particular input, but does not give the correct answer in general.
<p>
You're filling the knapsack with the items in the order of their relative value (v/w), so consider the following case when your knapsack is almost full (let's suppose there's still room for w=4):
</p>
<c>
nr w v v/w
1x 3 3.1 31/30 # case a
2x 2 2 1 # case b
</c>
<p>
Your algorithm will choose case 'a', increasing the full value by 3.1, however the correct choice is to choose case 'b' increasing the full value by 4. That's why you have to backtrack.
</p>
828578
828589