I have this piece of code that recursively gets all permutations of Strings in a set:
public static List<List<String>> combinations(List<String> strings)
{
if (strings.size() > 1)
{
List<List<String>> result = new ArrayList<List<String>>();
for (String str : strings)
{
List<String> subStrings = new ArrayList<String>(strings);
subStrings.remove(str);
result.add(new ArrayList<String>(Arrays.asList(str)));
for (List<String> combos : combinations(subStrings))
{
combos.add(str);
result.add(combos);
}
}
return result;
}
else
{
List<List<String>> result = new ArrayList<List<String>>();
result.add(new ArrayList<String>(strings));
return result;
}
}
If my arraylist holds too many values, it overflows the stack. I have since learned that transforming the algorithm from recursion to iterative would help me solve this memory issue since I would be handling the stack myself on the heap rather than using the native stack. I have never done this before and cannot wrap my head around how to do that with this problem. My problem is not as simple as the examples of seen of this transformation, so some hints as to the how I could achieve this would be much appreciated.