Norway


#include <iostream>

#include <list>

using namespace std;

 

void printList(list<pair<int, char>> const& list) {

    for (auto i: list)

        cout << R;(R; << i.second << “)” << i.first << ” “;

    cout << endl;

}

 

// Print all to a from of specified

void printWays(int arr[], int n, int sum, int target,

                            list<pair<int, char>> &list)

{

    // base case: if target is found, print result list

    if (sum == target)

    {

        printList(list);

        return;

    }

 

    // base case: No elements are left

    if (n < 0) {

        return;

    }

 

    // Ignore the current element

    printWays(arr, n 1, sum, target, list);

 

    // Consider the current element and subtract it from the target

    list.push_back({arr[n], ‘+’});

    printWays(arr, n 1, sum + arr[n], target, list);

    list.pop_back();    // backtrack

 

    // Consider the current element and add it to the target

    list.push_back({arr[n], ‘-‘});

    printWays(arr, n 1, sum arr[n], target, list);

    list.pop_back();    // backtrack

}

 

int main()

{

    // input array and target number

    int arr[] = { 5, 3, 6, 2 };

    int target = 6;

 

    int n = sizeof(arr)/sizeof(arr[0]);

    list<pair<int, char>> list;

 

    printWays(arr, n 1, 0, target, list);

 

    return 0;

}



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here