logo CodeStepByStep logo

threeSum

Language/Type: Java recursion backtracking
Related Links:

Write a recursive method named threeSum that accepts a list of integers and prints all combinations of three integers in the list that sum to 0. For example, if given the list [-1, 0, 1, 2, -1, -4], print the following lines of output:

[-1, 0, 1]
[-1, 2, -1]
[0, 1, -1]

You may print the lines of output in any order. The elements in each three-element sublist should appear in the same relative order that they appeared in the original list. Do not print duplicate lists; if the same exact sublist can be made in multiple ways, print it only once. If there are no combinations of three elements that sum to 0, print no output.

The list passed to your method must be back to its original state at the end of the call. Either do not modify it, or if you modify it, fully undo your modifications before the method returns.

Constraints: Do not declare any global variables. You can use any data structures you like, and your code can contain loops, but the overall algorithm must be recursive and must use backtracking. You are allowed to define other "helper" methods if you like; they are subject to these same constraints.

Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.