Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

The question I have is this Write in Java a method named possibleCombinations using recursion that takes two parameters list of integers and a summation

The question I have is this

Write in Java a method named possibleCombinations using recursion that takes two parameters list of integers and a summation that outputs all the possible combinations of numbers that equal the summation.

If the list that was passed was [1,2,3], possibleCombinations(list, 3) would output the following

[1, 1, 1]

[1, 2]

[2, 1]

[3]

And this is what I have so far; I keep getting a stackoverflow error.

import java.util.*;

public class possibleCombinations {

public static void possibleCombinations(List numbers, int summation) {

}

private static void possibleCombinations(List numbers, int summation, List possible, int total) {

if (total == summation) {

System.out.print(possible);

} else {

for (int number = 0; number < numbers.size(); number++) {

int newTotal = total + number;

if (newTotal < summation) {

possible.add(number);

possibleCombinations(numbers, summation, possible, total);

possible.remove(possible.size() - 1);

}

}

}

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions