java - How to list heap permutation -


i have function heap permutation want have list [[0, 1, 2], [1, 0, 2], [1, 2, 0], [0, 2, 1], [2, 0, 1], [2, 1, 0]] result [0, 1, 2, 1, 0, 2, 2, 0, 1, 0, 2, 1, 1, 2, 0, 2, 1, 0] please me

public static  list<integer> permute(int[] v, int n) {         //write code here         list b = new arraylist();             if (n==1) {                 (int j=0 ; j<v.length ; j++) {                     b.add(v[j]);                     }             }             else {                 (int i=0 ; i<n ; i++) {                     permute(v,n-1);                     if(n%2 == 0) swap(v,i,n-1);                     else swap(v,0,n-1);                 }             }             return b;         } 

in python, because can't test java code right now, , python's easier write quickly,
def permute(list): if not list: return [[]] result = [] entry in permute(list[1:]): in range(len(entry)): result.append(entry[:i]+list[i:i+1]+entry[i:]) return result hope helps, i'd have written java if test it.


here's algorithm this. stack overflow isn't site doing other people's homework, won't give entire answer.

you'll want function takes in list, , returns list of lists.
because you're solving recursively, first step base case. means, if problem has been reduced it's simplest form, should return obvious answer. in problem, simplest form of problem when call permute on empty list, , obvious answer return empty list (make sure list return correct type).
base case handled, need handle general case, , in proofs induction, can assume function works on smaller problems.

so, if have list [1,2,3,4], can use permute function on [2,3,4] , list of permutations of [2,3,4], , each of permutations, need add 1 @ each possible index.
once you've gone through smaller list created recursive call permute, , added first value of list each index of each list returned permute, you've finished, , can return list of lists generated.


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -