java - Permutation of an ArrayList of numbers using recursion -
i trying learn recursion creating permutation of arraylist:
{1,2,3}
but concept of recursive calls keeps going on head. know how iterative solution. there systematic way convert iterative solution recursive?
private static arraylist<arraylist<integer>> permutate(arraylist<integer> list) { arraylist<arraylist<integer>> result = new arraylist<arraylist<integer>>(); result.add(new arraylist<integer>()); (int = 0; < list.size(); i++) { arraylist<arraylist<integer>> current = new arraylist<arraylist<integer>>(); (arraylist<integer> l : result) { (int j = 0; j < l.size()+1; j++) { l.add(j, list.get(i)); arraylist<integer> temp = new arraylist<integer>(l); current.add(temp); l.remove(j); } } result = new arraylist<arraylist<integer>>(current); } return result; }
public static list<list<integer>> listpermutations(list<integer> list) { if (list.size() == 0) { list<list<integer>> result = new arraylist<list<integer>>(); result.add(new arraylist<integer>()); return result; } list<list<integer>> returnme = new arraylist<list<integer>>(); integer firstelement = list.remove(0); list<list<integer>> recursivereturn = listpermutations(list); (list<integer> li : recursivereturn) { (int index = 0; index <= li.size(); index++) { list<integer> temp = new arraylist<integer>(li); temp.add(index, firstelement); returnme.add(temp); } } return returnme; }
to test used:
public static void main(string[] args) throws exception { list<integer> intlist = new arraylist<integer>(); intlist.add(1); intlist.add(2); intlist.add(3); list<list<integer>> mylists = listpermutations(intlist); (list<integer> al : mylists) { string appender = ""; (integer : al) { system.out.print(appender + i); appender = " "; } system.out.println(); } }
which gave me output:
1 2 3 2 1 3 2 3 1 1 3 2 3 1 2 3 2 1
Comments
Post a Comment