logo CodeStepByStep logo


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

Write a recursive function named printSubVectors that accepts a reference to a vector of integer values as a parameter and that prints console output (to cout) displaying all possible sub-vectors that can be created from some subset of the vector's elements. For example, if a vector variable v stores the elements {1, 2, 3}, the call of printSubVectors(v); should print the following output to the console:

{2, 3}
{1, 3}
{1, 2}
{1, 2, 3}

Your function must print the sub-vectors in this same order, and the sub-vectors you print should preserve the order of the values from the vector. For example, the sub-vectors of {42, 23} should be listed as:

{42, 23}

You may assume the vector passed contains no duplicate values. If passed an empty vector, print only a single line containing the empty vector itself, {} .

Constraints: You may define helper functions if you like. You are allowed to construct exactly one auxiliary collection of your choice from the collections we have studied (one vector, set, map, stack, queue, array, etc.). That is, at most one collection can be constructed in total for each call a client makes on your function. Note that a compound collection, such as a Vector of Vectors, is considered to be more than one auxiliary collection in this context. Your function should not alter the contents of the vector that is passed as a parameter; declare your function's header in such a way to assure the client that you will not do so. You may not use any loops to solve this problem; you must use recursion.

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.