How to Find All Possible Subarrays of an Array

algorithmsprogramming-languagesrecursion

I am lost I just can't seem to get my head around backtracking/recursion approaches. I understand how simple recursion problems like factorials work I can even trace those by hand. But when it comes to backtracking problems I am so lost. I keep trying. its been 5 hours I have been reading various approaches on forums and stack exchange but nothing has clicked.

For instance say I have a array with [1,2,3,4] and my destination value is 5. I am trying to find all possible combinations that equal to my destination value.

I broke this problem down further to make it even more simple for my self to understand. First I can find all possible combinations of the array and then pass them to another function which checks if the sum of that array equals destination value and then only does it print it.

Can someone advice how to approach this? I am not looking for code/answer I want to be able to think and imagine this in my head clearly.

Best Answer

Lets take an array of size n. There 2n possible subarrays of this array. Lets take the example array of size 4: [1, 2, 3, 4]. There are 24 sub arrays.

Sub array of the empty set ([]) is the 0th one (0000). The subarray of [1], is the second one (0001), the subarray of [2] is the second one... (0010) and the subarray [1, 2] is the third one (0011). You should see where this is going.

No recursion is necessary for this. The set of the sub arrays is the binary representation of the the nth value ranging from 0 to 2n - 1.

With this realization, the generation of all of the subarrays for a given arrays should be a trivial matter of iterating of the integers and looking at them as bit fields for if a particular element is in the subarray or not.

See also Number of k combinations for all k on Wikipedia.


I would point out that this is probably the right way to do it in C and similar languages. Trying to force recursion, lists, and backtracking onto what would otherwise be a simple iterative problem with a clear and understandable answer may not the best approach.

Note that other proposed answers to this quickly become functional programming examples and solutions. Functional programming is great. However, in a language not suited for such trying to force this paradigm of programming on it would be akin to writing C code in Lisp - it might not be the best way to approach the problem.

I should further point out that the problem hinted at in the question is:

For instance say I have a array with [1,2,3,4] and my destination value is 5. I am trying to find all possible combinations that equal to my destination value.

This is a well known problem known as the subset sum problem and has a number of approaches to solve it... generating all the subsets of the array is not required (or even desired) for the faster approaches to solve it.

Related Topic