递归数排列时间复杂度

时间:2019-04-13 03:03:56

标签: java time-complexity

我想出了一段代码,它可以递归地生成数字排列,但不确定时间的复杂性,有人知道吗?

 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);
        }
    }

1 个答案:

答案 0 :(得分:-1)

使用Integer而不是使用NumberString,对您有很大帮助。

您可以使用this from GeeksForGeeks代码。

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是需要帮助的,为什么,它为什么运行起来有些复杂?