简体   繁体   English

打印字符串排列的算法-运行时间分析

[英]Algorithm to print String Permutations - Running Time Analysis

I have the following code to print permutations of a given string. 我有以下代码来打印给定字符串的排列。 [For simplicity and not to loose focus on what I am trying, lets assume there are not duplicates characters in the string] [为简单起见,不要将重点放在我正在尝试的内容上,假设字符串中没有重复的字符]

public static int count = 0;

public static void permute(String soFar, String strLeft) {

    if(strLeft.length() == 1) {
        soFar += strLeft;
        System.out.println(++count + " :: " + soFar);
    }

    for(int i=0; i<strLeft.length(); i++) {
        permute(soFar + strLeft.charAt(i), strLeft.substring(0,i) + strLeft.substring(i+1));
    }
}

/**
 * @param args
 */
public static void main(String[] args) {
    String input = "abcd";
    permute("",input);
}

I am trying to figure out the running time of this code. 我试图弄清楚这段代码的运行时间。

My chain of thoughts so far: Trying to write a recurrence, 到目前为止,我的想法是:尝试重复写作,

T(n) = n * T(n-1) + O(n) for n > 1
     = 1                 for n = 1

There are n! 有n! permutations, but the number of recursive calls are greater than n!. 排列,但递归调用的数量大于n!。 In-fact for the example where input string is "abcd" , ie 4 characters, the number of calls to the permute function is 65. 实际上,在输入字符串为“ abcd”(即4个字符)的示例中,对permute函数的调用数为65。

Any pointers on how I should go about finding the running time of this code? 关于如何找到该代码的运行时间的任何指示?

Well, first of all, you make redundant calls. 好吧,首先,您要进行冗余呼叫。 If there is only one character left, you emit a solution. 如果只剩下一个字符,则发出解决方案。 But then you will still call permute with an empty string and spoils the calling count. 但是,您仍然会使用空字符串调用permute ,并破坏调用计数。

My first improvement would be to add an else to the if clause. 我的第一个改进是在if子句中添加else

public static void permute(String soFar, String strLeft) {

    if(strLeft.length() == 1) {
        soFar += strLeft;
        System.out.println(++count + " :: " + soFar);
    }
    else {
        for(int i=0; i<strLeft.length(); i++) {
            permute(soFar + strLeft.charAt(i), strLeft.substring(0,i) + strLeft.substring(i+1));
        }
    }
}

This cuts down the amount of calls to 41. And to count the number of calls, construct the calling tree and count the nodes. 这样可以将调用数量减少到41。并且要计算调用数量,构造调用树并计算节点数。 As each call is done by removing one character from the string, there are: 由于每个调用都是通过从字符串中删除一个字符完成的,因此有:
1 calls of length 4, 长度为4的1个呼叫
4 calls of length 3, 4个长度为3的通话,
12 calls of length 2 and 长度为2的12个呼叫
24 calls of length 1 24个长度为1的呼叫

Which sums up to 41. Voilá. 总计为41。Voilá。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM