void perm(String prefix, String str) if str.length == 0 print prefix else{ for i=0 i < str.length i++ perm(prefix + str.charAt(i), removeIndex(i, str));
// generate all permutation from given char[], e.g. ['a', 'b'] public static void permutation(char[] arr, int index){ if(index == arr.length){ Aron.printArray(arr); }else{ if(arr != null){ int len = arr.length; for(int i=index; i < len; i++){ Aron.swap(arr, i, index); permutation(arr, index + 1); Aron.swap(arr, i, index); } } } }
0. Previous algorithm does not generate sorted order permutations lexicographically. 1. Following algorithm generates sorted order permutations // permutations are in sorted ordering in lexicographically public static void permutationPrefix(String prefix, String str){ if(str != null){ if(str.length() == 0){ Print.p(prefix); }else{ int len = str.length(); for(int i=0; i< len; i++){ String s = str.charAt(i) + ""; permutationPrefix(prefix + s, remove(str, i)); } } } } public static String remove(String str, int index){ String s = ""; for(int i=0; i< str.length(); i++){ if(i != index) s += str.charAt(i) + ""; } return s; }
void permutate(int* array, int size, int k) { if(k == size) { for(int i=0; i < size; i++) std::cout< < "["< < array[i]< < "] "; std::cout<< std::endl; } else { for(int i=k; i< size; i++) { swap(array, i, k); for(int j=0; j< k; j++) std::cout< <"[--]"; std::cout<<"(i="<< i < < ",k="< < k < <")"<< std::endl; permutate(array, size, i+1); swap(array, i, k); } } }
public static void permPrefixChoose(String prefix, String s, int k, HashSetset){ if(s != null){ if(s.length() == k){ set.add(s); }else{ for(int i=0; i< s.length(); i++){ String str = s.charAt(i) + ""; permPrefixChoose(prefix + str, dropIndex(i, s), k, set); } } } }
Explanation: 1 2 3 4 1 2 3 4 2 3 4 3 4 4 [] 1 (c(n-1)) 2 (c(n-1)) 3(c(n-1)) 4(c(n-1)) 2 3 4 3 4 4 3 4 4 4 combination::Int -> [a] -> [[a]] combination 0 _ = [[]] combination n cx = [ x:cy | x:cx' <- L.tails cx ,cy <- combination (n-1) cx']
public static void combination(Listprefix, List ls, Integer n){ if( n == 0){ printList(prefix); }else{ for(int i = 0; i < ls.size(); i++){ var rs = drop(i + 1, ls); var a = ls.get(i); combination(append(prefix, a), rs, n - 1); } } }