Print all the permutations of a string in C

前端 未结 8 1450
自闭症患者
自闭症患者 2020-11-29 04:06

I am learning backtracking and recursion and I am stuck at an algorithm for printing all the permutations of a string. I solved it using the bell algorithm for permutation b

8条回答
  •  情深已故
    2020-11-29 04:38

    Recursion really simplifies it:

    public static void permutation(String str) 
    { 
        permutation("", str); 
    }
    
    private static void permutation(String prefix, String str) 
    {
        int n = str.length();
        if (n == 0) {
            System.out.println(prefix);
        } else {
            for (int i = 0; i < n; i++)
                permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
        }
    }
    

提交回复
热议问题