Find the Series - ARRAY_2

Problem Link : ARRAY_2

Problem :

You are given an array arr[] of positive integers and a sum k , you have to find all the combinations in arr[] whose sum is equal to k . Also you have to print the combinations in sorted manner as well as in ascending order. If there is no combinations found print Empty
Input Format
First line contains the sum k
Second line contains the size of the array n

Output Format
Print the combinations else print Empty

Sample Input 1
8
4
2
4
6
8

Sample Output 1
2 2 2 2
2 2 4
2 6
4 4
8

Sample Input 2
1
4
2
4
6
8

Sample Output 2
Empty

Solution:

#include<bits/stdc++.h>
using namespace std;

void findNumbers(vector& ar, int sum,
vector<vector >& res,
vector& r, int i)
{

if (sum < 0)
    return;


if (sum == 0)
{
    res.push_back(r);
    return;
}


while (i < ar.size() && sum - ar[i] >= 0)
{


    r.push_back(ar[i]);
    findNumbers(ar, sum - ar[i], res, r, i);
    i++;


    r.pop_back();
}

}

vector<vector > combinationSum(vector& ar,
int sum)
{

sort(ar.begin(), ar.end());


ar.erase(unique(ar.begin(), ar.end()), ar.end());

vector<int> r;
vector<vector<int> > res;
findNumbers(ar, sum, res, r, 0);

return res;

}

int main()
{

int i,a[10];

int sum,x;
cin>>sum;
cin>>x;
 for(i=0;i<x;i++)
 {
   cin>>a[i];
 }
 vector<int> ar;
 for(i=0;i<x;i++)
 {
   ar.push_back(a[i]);
 }

int n = ar.size();
vector<vector<int> > res = combinationSum(ar, sum);


if (res.size() == 0)
{
    cout << "Empty";
    return 0;
}


for (int i = 0; i < res.size(); i++)
{
    if (res[i].size() > 0)
    {
        for (int j = 0; j < res[i].size(); j++)
            cout << res[i][j] << " ";
        cout << "\n";
    }
}

}