Use Backtracking strategy to solve 0/1 Knapsack problem.

 #include <stdio.h>


#define MAX 20


int n, W;

int weights[MAX], profits[MAX];

int maxProfit = 0;


// Backtracking function

void knapsack(int i, int currentWeight, int currentProfit) {

    if (i == n) {

        if (currentWeight <= W && currentProfit > maxProfit) {

            maxProfit = currentProfit;

        }

        return;

    }


    // Include the item

    if (currentWeight + weights[i] <= W) {

        knapsack(i + 1, currentWeight + weights[i], currentProfit + profits[i]);

    }


    // Exclude the item

    knapsack(i + 1, currentWeight, currentProfit);

}


// Main function

int main() {

    printf("Enter number of items: ");

    scanf("%d", &n);


    printf("Enter weights of items: ");

    for (int i = 0; i < n; i++)

        scanf("%d", &weights[i]);


    printf("Enter profits of items: ");

    for (int i = 0; i < n; i++)

        scanf("%d", &profits[i]);


    printf("Enter capacity of knapsack: ");

    scanf("%d", &W);


    knapsack(0, 0, 0);


    printf("Maximum profit: %d\n", maxProfit);

    return 0;

}

Output:


Comments