Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void knapsackDynamic(std::vector<Item> items, const int knapsackCapacity) {
- const int numberOfItems = items.size();
- // DP matrix initialization
- int** DPmatrix = new int* [numberOfItems + 1]{};
- for (int itemIndex = 0; itemIndex <= numberOfItems; ++itemIndex) {
- DPmatrix[itemIndex] = new int[knapsackCapacity + 1]{};
- }
- printMatrix(DPmatrix, numberOfItems + 1, knapsackCapacity + 1);
- for (int itemIndex = 1; itemIndex <= numberOfItems; ++itemIndex) {
- int value = items[itemIndex - 1].value;
- int weight = items[itemIndex - 1].weight;
- for (int slot = 0; slot <= knapsackCapacity; ++slot) {
- if (weight > slot) {
- DPmatrix[slot][itemIndex] = DPmatrix[itemIndex - 1][slot];
- }
- else {
- int previous = DPmatrix[itemIndex - 1][slot];
- int possibleNext = DPmatrix[itemIndex - 1][slot - weight] + value;
- DPmatrix[itemIndex][slot] = std::max(previous, possibleNext);
- }
- }
- }
- std::cout << '\n';
- printMatrix(DPmatrix, numberOfItems + 1, knapsackCapacity + 1);
- // Release allocated memory
- for (int i = 0; i <= numberOfItems; ++i) {
- delete[] DPmatrix[i];
- }
- delete[] DPmatrix;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement