logo CodeStepByStep logo


Language/Type: C++ recursion backtracking
Related Links:
Author: Marty Stepp (on 2016/06/16)

You have a bag of weights and a balance. On one side of the balance is a target weight. Write a function named canBalance that accepts two parameters: an integer representing the target weight that you want to balance, and a vector of positive integers, which represent your weights. Your function 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:


You are allowed to modify the vector 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.

Type your C++ solution code here:

This is a function problem. Write a C++ function as described. Do not write a complete program; just the function(s) above.

You must log in before you can solve this problem.

Log In

Need help?

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.

© Marty Stepp, all rights reserved.