繁体   English   中英

如何计算这种递归方法的时间复杂度?

[英]how to calculate time complexity for this recursive method?

对于方法

static void replace(char biStr[], int index){
        if (index == biStr.length){
            System.out.println(biStr);
            return;
        }
        //print result when reach the end of the array
        if (biStr[index] == '*'){
            for (char ch = '0'; ch <= '1'; ch++) {
                 biStr[index] = ch;
                 replace(biStr, index+1);
                 biStr[index] = '*';
            }
            // replace *
        }
        else
            replace(biStr, index + 1);
            //if the digit is not *, go to next digit
    }

其中 biStri 是一个 0,1, 的数组 例如 {1, ,0,0, , ,1}。 并且该方法得到了用0或1替换*的所有可能性结果。使用同一个例子,它会得到8个不同的结果,因为有3个*,2^3 = 8。这是否意味着时间复杂度也是2^ 3? 如果不是,如何计算? 空间复杂度是biStr.length,对吗?

最坏的情况是 2^(n+1)。 最好的情况是 n+1。 由于它是就地替换,因此程序的空间复杂度为 O(n)。

暂无
暂无

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

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