current position:Home>C + + recursive knapsack problem

C + + recursive knapsack problem

2022-01-27 02:09:01 laocooon

#include <iostream>
using namespace std;
int w[100];
int beibao(int s, int n)
{
    if (s == 0) {
        cout << s << endl;;
        return 1;
    }
    if (s < 0 || s>0 && n < 1)
    {
        cout << s << " " << n << endl;
        return 0;
    }


    if (beibao(s - w[n], n - 1))
    {
        cout << s << " " << n << endl;
    return 1;
}
    cout << s << " " << n << endl;
    return beibao(s, n - 1);
}
int main()
{
    int s, n, i;
    cin >> s;
    cin>> n;

    for (i = 1; i <= n; i++)
        cin >> w[i];
    
    if (beibao(s, n) == 1)
        cout << "YES" << endl;
    else
        cout << "NO" << endl;
    return 0;
}

copyright notice
author[laocooon],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270208598528.html

guess what you like

Random recommended