Блог пользователя DonMichaelCorleone

Автор DonMichaelCorleone, история, 10 лет назад, По-английски

How to print all the solutions of a knapsack DP problem solved by recursive manner ? Where every element can be picked more than one time.

I only can print the result ( like "yes"/"no", maximum sum/minimum cost etc, number of ways etc).

Sorry for my bad English.

  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +1 Проголосовать: не нравится

Well you can, instead of having just one array "dp[][].." make also another array "ans[][]...", where you will keep "even" (like what you did). You can keep there for example "7", like you kept 7 of actual element.

Afterward, you can execute function, which is very similar to your "dynamic programming function", anyway instead of making "multiple choices", you will do exactly what is written in "ans[][].." array.

This will lead you to "linear" simulation of BEST solution, where you will be at every node and you might print whatever you want there (for example "ans" or path or...)

Don't hesitate to ask more!

Good Luck & Have nice day ^_^

»
10 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

you can also just add another parameter ( a string) in the recursion to tell you what element you picked

so assume at this recursion step, you want to add 2 quantities of object number 2 to the knapsack, just append "22" to the resulting string, then you can either save it in another 2D array (like what user::-morass- said) , OR keep a global vector of string, once we found a solution, just push it to the global vector then print it in the main function