编辑代码

#include <stdio.h>
#include <math.h>

struct Commodity {
	char name[100];
	int weight;
	int value;
};

void getMaxValueForBackpack(int capacity, struct Commodity commodities[], int commodityCount) {

    int maxValue = -1;
    int maxValuePos = -1;
	int i;
	
    for ( i = 0; i < exp2(commodityCount); i++) {
    	printf("%d\n", i);
        int pos = i;
        int weight = 0;
        int value = 0;
        int curBit = 0;

        while (pos > 0) {
            if ((pos & 1) == 1) {
                weight += commodities[curBit].weight;
                value += commodities[curBit].value;
                printf("%d %d\n", weight, value);
            }
            pos = pos >> 1;
            ++curBit;
        }

        if (weight <= capacity && maxValue < value) {
            maxValue = value;
            maxValuePos = i;
            printf("%d %d\n", maxValue, maxValuePos);
        }
    }

    if (maxValuePos > 0) {
        int curBit = 0;
        printf("I want to put \n");
        while (maxValuePos > 0) {
            if ((maxValuePos & 1) == 1) {
				printf("%s(%d,%d);\n",
					commodities[curBit].name, commodities[curBit].weight, commodities[curBit].value);
            }
            maxValuePos = maxValuePos >> 1;
            ++curBit;
        }
    }
}

int main() {
    struct Commodity commodities[] = {
        {"吉他", 15, 1500},
        {"笔记本电脑", 20, 2000},
        {"音响", 30, 3000}
    };
    getMaxValueForBackpack(35, commodities, 3);

    struct Commodity fourcommodities[] = {
        {"吉他", 15, 1500},
        {"笔记本电脑", 20, 2000},
        {"音响", 30, 3000},
        {"苹果手机", 10, 2000}
    };

    getMaxValueForBackpack(40, fourcommodities, 4);

	return 0;
}