Combination Sum
You are given an array/list ARR of N distinct positive integers. You are also given a non-negative integer B.
Your task is to find all unique combinations in the array whose sum is equal to B. A number can be chosen any number of times from array/list ARR.
Elements in each combination must be in non-decreasing order.
For example:
Let the array ARR be [1, 2, 3] and B = 5. Then all possible valid combinations are-
(1, 1, 1, 1, 1)
(1, 1, 1, 2)
(1, 1, 3)
(1, 2, 2)
(2, 3)
Input Format
The first line of input contains an integer ‘T’ denoting the number of test cases to run. Then the test case follows.
Then the first line of each test case contains two space separated integers ‘N’ and ‘B’ denoting the number of elements in the array/list and the target sum respectively.
The second line of each test case contains N space separated integers the elements of array/list ARR.
Output Format :
For each test case, print all possible valid combinations in separate lines. You can print combinations in any order. Elements in each combination must be in non-decreasing order.
Output for each test case will be printed in a new line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 5
1 <= N <= 15
1 <= B <= 20
1 <= ARR[i] <= 20
Time Limit: 1sec
CodingNinjas
author
2y
This problem can be solved using recursion.
Steps :
1. Sort the array in increasing order.
2. Next, remove all the duplicates from array.
3. Now, use recursion and backtracking
(A) If at any time sub-pr...read more
CodingNinjas
author
2y
Recursive Approach
We can use a backtracking approach to generate all the valid combinations.
The approach will be:
- We will sort the array/list ‘ARR’ in ascending order.
- Let the current sum of the combi...read more
Help your peers!
Add answer anonymously...
Top MakeMyTrip Senior QA Engineer interview questions & answers
Popular interview questions of Senior QA Engineer
Top HR questions asked in MakeMyTrip Senior QA Engineer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app