A 0-1 Knapsack Problem

/*
Input two integers M and N. Find all possible ways that the sum of numbers chosen from 1, 2,3,...N equals M. Print all possible combinations.
*/



#include

using namespace std;

int count = 0;
int N ;
int M ;
int *result;

void bag01(int m, int n)
{
    if (m < n) n=m;
    for (int i = n; i>0; i--)
    {
        for( int j =0 ; j < n; j++)
           result[j] = 0;
        result[i-1] = 1;
        if ((m-i) > 0  ) bag01(m-i, i-1);

        if ( (m-i) == 0)
        {
             for ( int k = 0; k < N; k++)
            {
                if(result[k]) cout << k+1 << " " ;
            }
            cout << endl;

        count++;
        }
    }
}

int main()
{
    cout << " M =  ";
    cin >> M;
    cout << " N = ";
    cin >> N;
    result = new int[N];

    for (int i = 0; i < N; i++)
        result[i] = 0;
    cout << "The possible ways are: " << endl;
    bag01(M, N);
    delete [] result;
    cout << count << endl;
    return 0;
}

No comments: