Given an array of 2 numbers and a sum d find all the sequence of numbers that equal that sum

We are given an array of 2 elements and we are required to find every sequence where their sum is equal to d using recursion

For example given array v[]={2,6} and d=10 the function should print out 4 solutions
{2,2,2,2,2} {2,2,6} {2,6,2} {6,2,2}

Thing is i cant think of any idea on how i might solve this so i ask here. If not a complete code then can i ask for some ideas on how to think around this problem?

>Solution :

This is a standard recursion question which goes by the name of Combination sum on leetcode but with a slight difference that elements array size is not fixed to 2. I personally have solved this question in java.

We are using recursion since we have choices in elements to pick or not pick.
The basic idea is you pick an element, subtract it from the target. Now you can either move to next element, or choose the same element.
You choose the same element when target is still smaller than the current element. If not, move to picking up the next element.

https://leetcode.com/problems/combination-sum/

Here is the link for the question.
And this is how I have solved it in java. Language should not matter, you can definitely try in C by yourselves.

class Solution {
    public List<List<Integer>> answer = new ArrayList<>();
    
    public void solve(int[] candidates, int index, int target, ArrayList<Integer> path){
        if(index>=candidates.length || target < 1){
            if(target==0){
                ArrayList<Integer> ans = new ArrayList<>(path);
                answer.add(ans);
            }
            return;
        }
        solve(candidates, index+1, target, path);
        ArrayList<Integer> p = new ArrayList<>(path);
        p.add(candidates[index]);
        solve(candidates, index, target-candidates[index], p);
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        solve(candidates, 0, target, new ArrayList<>());
        return this.answer;
    }
}

For explanation about the answer, if you need a video
here you go, the best video explanation I have found

https://youtu.be/OyZFFqQtu98?list=PLgUwDviBIf0rGlzIn_7rsaR2FQ5e6ZOL9

Leave a Reply