C++: 背包问题

题目:
背包问题:假设有一个能装入总体积为T的背包和n件体积分别为W1,W2,…,Wn的物品,能否从n件物品中挑选若干件恰好装满背包,使Wi1+Wi2+…+Win=T,要求找出所有满足上述条件的解。

思路:
采用循环内调用递归的方式,同时利用回溯的思想,将情况遍历一遍并取出符合条件的输出。

代码:

# include 
# include 
using namespace std;

int sum = 0;  // The sum of all items
int T; // The volumn of bag
int count1 = 0; // The number of conditions

vector<int> temp;  // write down the items that put in bag

/* print the items with the sum of T */
void print() {
    count1++;
    cout << "condition" << count1 << ": ";
    cout << "(";
    for (int i = 0; i < temp.size(); i++) {
        cout << temp[i];
        if (i != temp.size()-1) {
            cout << ",";
        }
    }
    cout << ")" << endl;
}

/* The core realization */
void calculate(int* items, int num, int current) {
    sum += items[current];
    if (sum > T) {   // if sum > T, subtract the value we add just now
        sum -= items[current];
        return;
    } else {  // if not, push it into temp
        temp.push_back(items[current]);
    } // if sum == T, print the result
    if (sum == T) {
        print();
        sum -= items[current];  // remember to subtract the current item
        temp.pop_back();  // also pop it from the temp
        return;
    }
    for (int i = current+1; i < num; i++) { // for + recursive can traverse all situation
        calculate(items, num, i);
    }
    temp.pop_back();   // after for-loop ending, you need to pop the current item
    sum -= items[current]; // also you need to subtract it
}

int main(void) {
    int num;  // the number of item you want to enter
    cout << "Please enter the volume of the bag "
         << "together with the number of item:\n";
    cin >> T >> num;
    int* items = new int[num];
    for (int i = 0; i < num; i++) {
        cin >> items[i];
    }
    for (int i = 0; i < num; i++) {   // for-loop
        calculate(items, num, i);
        sum = 0;  // after every loop ending,you need to set the sum to 0
        temp.clear(); // also,you need to clear the temp
    }
    delete[] items;
    return 0;
}

因为代码部分有详细注释,这里我就不仔细解释了。不过这道题有些地方还是要注意的:比如什么时候需要把temp清空什么时候要弹出temp中的元素什么时候需要将sum减去某个值等。


以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!


你可能感兴趣的:(C++)