1

Possible Duplicate:
Design patterns for converting recursive algorithms to iterative ones

I can only figure out a recursive way: how to transform it into iteration? for simplicity, my recursive way only find the result value.

#include<iostream>
//0-1 bag
using namespace std;
int weight[5]={50,30,45,25,5};
int value[5]={200,180,225,200,50};

int valueAfterTake(int objectNO, int bagSpaceLeft)
{
    int take,notTake;
    if(objectNO < 0)
    {
        return 0;
    }
    else
    {
        take = value[objectNO] + valueAfterTake(objectNO - 1,bagSpaceLeft - weight[objectNO]);
        notTake = valueAfterTake(objectNO - 1, bagSpaceLeft);
    }
    if(weight[objectNO] > bagSpaceLeft)
    {
        return notTake;
    }

    if(take > notTake)
    {
        return take;
    }
    else
    {
        return notTake;
    }
}


int main()
{
    cout<<valueAfterTake(4,100)<<endl;
    return 0;
}
Community
  • 1
  • 1
CarmeloS
  • 7,868
  • 8
  • 56
  • 103

2 Answers2

1

Given what you really want, I think this is a duplicate question of Design patterns for converting recursive algorithms to iterative ones

Community
  • 1
  • 1
ninjagecko
  • 88,546
  • 24
  • 137
  • 145
1

From the algorithm in 0-1 knapsack problem can put everything in a table of i and w.
Make a two diminutional table filled with NO_VALUE constants(-1 or something like that).
Then when you need to get the value for m[i, w] you find what indexes from the table you need, check if their computed(by comparing to NO_VALUE), and computing them if their not.
Here you will gain much less code execution in tradeoff for space because you will never compute the same value twice.
edit:
In addition, from there you can continue to find patterns, like you're always using one row, or one diagonal and such and cut out everything you don't need in the table.

Daniel
  • 30,896
  • 18
  • 85
  • 139