简体   繁体   English

字符串组合算法的复杂度(作为递归)

[英]Complexity of string combination algorithm (as recursive)

I have a method like the following: 我有如下方法:

How can I calculate the Big-O? 如何计算Big-O?

O(2 n ) or O(n n )?? O(2 n )或O(n n )??

Thanks. 谢谢。

public static void combination(String str, int r) 
{

    int len = str.length();

    if (len == r) myList.add(str);
    if (len == 1) return;

    String newStr = null;
    for (int i = 0; i < len; i++) {
        newStr = str.substring(0, i) + str.substring(i + 1);
        combination(newStr, r);
    }
}

(since this is homework, just hints!) (由于这是家庭作业,因此只是提示!)

Have you worked out what the code does yet? 您知道代码的用途了吗? How much output does it produce for a given input? 给定输入会产生多少输出?

That must be a lower-bound on the running time of the algorithm since there's no way you can run quicker than the number of outputs you must generate. 这必须是算法运行时间的下限,因为您无法以比必须生成的输出数量更快的速度运行。 Perhaps the easiest way would be to look at the size of the list for various inputs and use that as a basis. 也许最简单的方法是查看各种输入的列表大小并将其作为基础。

这是我的提示。

int n = str.length();

Try to transform the algorithm into an equation, something like X(n+1) = Function(X(n)) and resolve the equation. 尝试将算法转换为方程式,例如X(n + 1)= Function(X(n))并求解方程式。

If you can't, try with the initial case X(1) = Function(X(0)), then X(2) = Function(X(1)), etc... You will notice a pattern (and may be the answer is something different than O(2^n) or O(n^n)). 如果不能,请尝试以下情况:X(1)= Function(X(0)),然后X(2)= Function(X(1)),依此类推...您会注意到一种模式(并且可能是答案与O(2 ^ n)或O(n ^ n))不同。

Just hints !!! 只是提示!

For not-so-complex scenario, I use counter. 对于不太复杂的情况,我使用计数器。

public class Combination {

    private static int count;

    public static void main(String[] args) {

        String[] inputs = new String[] {"12345", "1234", "123", "12", "1"};
        for(String input : inputs){
            count = 0;
            System.out.print("output for " + input + " is:");
            combination(input);
            System.out.println("\nCount for input:" + input + " is " + count);  
        }

    }

    private static void combination(String input) {
        combination("", input);
    }

    private static void combination(String prefix, String input) {
        System.out.print(prefix + " ");
        count++;
        int n = input.length();
        for(int i = 0; i < n; i++){
            combination(prefix + input.charAt(i), input.substring(i + 1));
        }
    }
}

The solution is indeed O(2^n) 解的确是O(2 ^ n)

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

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