recursive Number permutation Time complexity

75Thunder :

I came up with a piece of code that recursively generates number permutations but am unsure of the time complexity, does any one know what it is?

 private static void maketree(int i) {
        Node<Integer> head = new Node<Integer>(0);
        ArrayList<Integer> hasLeft = new ArrayList<Integer>();
        ArrayList<ArrayList<Integer>> permutations = new ArrayList<ArrayList<Integer>>();

        for (int tmp = 1; tmp < i; tmp++) {
            hasLeft.add(tmp);
        }

        for (Integer t = 0; t < hasLeft.size(); t++) {
            head.addChild(hasLeft.get(t));
            ArrayList<Integer> start = new ArrayList<Integer>();
            start.add(0);
            fillTree(head.getChildren().get(t), (ArrayList<Integer>) hasLeft.clone(), start, permutations);
        }
    }

    private static void fillTree(Node<Integer> n, ArrayList<Integer> hasLeft, ArrayList<Integer> start,
            ArrayList<ArrayList<Integer>> permutations) {

        ArrayList<Integer> current = (ArrayList<Integer>) start.clone();
        current.add(n.getData());
        hasLeft.remove(n.getData());
        if (hasLeft.isEmpty()) {
            permutations.add(current);
        }

        for (Integer i = 0; i < hasLeft.size(); i++) {
            n.addChild(hasLeft.get(i));
            fillTree(n.getChildren().get(i), (ArrayList<Integer>) hasLeft.clone(), current, permutations);
        }
    }
Maifee Ul Asad :

Instead of using Integer or Number, use String, that will help you a lot.

And you can use this from GeeksForGeeks code.

public class Permutation { 
public static void main(String[] args) 
{ 
    String str = "ABC"; 
    int n = str.length(); 
    Permutation permutation = new Permutation(); 
    permutation.permute(str, 0, n - 1); 
} 

/** 
 * permutation function 
 * @param str string to calculate permutation for 
 * @param l starting index 
 * @param r end index 
 */
private void permute(String str, int l, int r) 
{ 
    if (l == r) 
        System.out.println(str); 
    else { 
        for (int i = l; i <= r; i++) { 
            str = swap(str, l, i); 
            permute(str, l + 1, r); 
            str = swap(str, l, i); 
        } 
    } 
} 

/** 
 * Swap Characters at position 
 * @param a string value 
 * @param i position 1 
 * @param j position 2 
 * @return swapped string 
 */
public String swap(String a, int i, int j) 
{ 
    char temp; 
    char[] charArray = a.toCharArray(); 
    temp = charArray[i]; 
    charArray[i] = charArray[j]; 
    charArray[j] = temp; 
    return String.valueOf(charArray); 
} 
} 

Internet is for help, take it, why just run in some complexity ?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=307839&siteId=1