

In lexicographical order, combination/array ‘a’ comes before array ‘b’ if at the first index 'i' where 'a[i]' differs from 'b[i]', 'a[i]' < 'b[i] or length of 'a' is less than 'b'.
Input: ‘arr’ = [1, 2, 3, 1], ‘target’ = 5.
Output: [[1,1,3], [2,3]]
Explanation:
All possible valid combinations with sum = 5 in lexicographical order are -:
(1, 1, 3)
(2, 3)
Then the first line of input contains two space-separated integers ‘n’ and ‘target’ denoting the number of elements in ‘arr’ and the ‘target'.
The second line of input contains 'n' space-separated integers the elements of array ‘arr’.
Print all possible valid combinations in a separate line in the lexicographical order. Elements in each combination must be in non-decreasing order.
You do not need to print anything, it has already been taken care of. Just implement the given function.
First, sort the given array in non-decreasing order, it will help to generate combinations in non-decreasing order. There will be 2 ^ N possible combinations of the given array, We create a vector ‘result’ and then we one by one check for all possible combinations, whether the sum of its elements is equal to ‘target’ or not. If the sum of the combination is equal to ‘target’, we will append it in vector ‘result’.
We finally sort vector ‘result’ in lexicographical order and remove all duplicates from it.
We can find all combinations of array both iteratively or recursively, Here, we will be using the iterative approach only.
Algorithm:
This problem can be solved using backtracking, The idea is to incrementally build combinations to the solution set, and abandon a combination ("backtrack") as soon as it determines that the combination cannot achieve the target sum. In order to avoid duplicates, we cannot consider each element separately. We need to consider a group of the unique integer while backtracking.
We first create an array ‘counters’ that will keep the frequency of each element in the array.
After that, we start from smallest to the largest unique integer in ‘arr’ and for each unique integer, we try to include each of its number of occurrence (from largest to smallest) in combination if it can lead to the target sum, otherwise backtrack to determine other such combinations. Note, the order i.e smallest to largest unique integer and largest to smallest in occurrence will ensure that combination will generate in lexicographical order.