logo CodeStepByStep logo

canBalance

Language/Type: Java recursion backtracking
Related Links:

You have a bag of weights and a balance. On one side of the balance is a target weight. Write a method named canBalance that accepts two parameters: an integer representing the target weight that you want to balance, and a list of positive integers, which represent your weights. Your method should return true if you can balance the scales, and false otherwise.

For example, if you are trying to balance a target weight of [5] using a bag of [1, 2, 6], this returns true because you can put the [1] with the [5], the [6] on the other side, and leave the [2] unused. Or, as shown in the figures below, if you had a bag of [1, 3] you could measure a weight of 4 or 2 by the following two arrangements:

figure
figure

You are allowed to modify the list passed in as the parameter as you compute the answer, as long as you restore it to its original form by the time the overall call is finished. Do not use any loops in solving this problem. Your code should use recursive backtracking.

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.