Permutation algorithm for array of integers in Java

前端 未结 9 2046
-上瘾入骨i
-上瘾入骨i 2020-11-29 12:56

I have a working example to generate all char permutations in a String as below:

static ArrayList permutations(String s) {
        if (s == nul         


        
9条回答
  •  借酒劲吻你
    2020-11-29 13:06

    //Here is a recursive version that was not to hard to commit to human memory ! O(n!) permutations.

    public static Set getPermutationsRecursive(Integer[] num){
        if (num == null)
            return null;
    
        Set perms = new HashSet<>();
    
        //base case
        if (num.length == 0){
            perms.add(new Integer[0]);
            return perms;
        }
    
        //shave off first int then get sub perms on remaining ints.
        //...then insert the first into each position of each sub perm..recurse
    
        int first = num[0];
        Integer[] remainder = Arrays.copyOfRange(num,1,num.length);
        Set subPerms = getPermutationsRecursive(remainder);
        for (Integer[] subPerm: subPerms){
            for (int i=0; i <= subPerm.length; ++i){ // '<='   IMPORTANT !!!
                Integer[] newPerm = Arrays.copyOf(subPerm, subPerm.length+1);
                for (int j=newPerm.length-1; j>i; --j)
                    newPerm[j] = newPerm[j-1];
                newPerm[i]=first;
                perms.add(newPerm);
            }
        }
    
        return perms;
    }
    

提交回复
热议问题