开发者

Complexity of string combination algorithm (as recursive)

I have a method like the following:

How can I calcu开发者_JAVA百科late the Big-O?

O(2n) or O(nn)??

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.


Here's my hint.

int n = str.length();


Try to transform the algorithm into an equation, something like X(n+1) = Function(X(n)) and resolve the equation.

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)).

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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜