字符串组合算法的复杂性(递归)
我有一个如下的方法:
如何计算 Big-O?
O(2n) 还是 O(nn)?
谢谢。
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);
}
}
I have a method like the following:
How can I calculate 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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
(因为这是家庭作业,只是提示!)
您已经弄清楚代码的作用了吗?对于给定的输入,它会产生多少输出?
这必定是算法运行时间的下限,因为您无法运行得比必须生成的输出数量更快。也许最简单的方法是查看各种输入的列表的大小并将其用作基础。
(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.
尝试将算法转换为方程,例如 X(n+1) = Function(X(n)) 并求解方程。
如果不能,请尝试使用初始情况 X(1) = Function(X(0)),然后 X(2) = Function(X(1)) 等...您会注意到一种模式(并且可能答案与 O(2^n) 或 O(n^n)) 不同。
只是提示!
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 !!!
对于不太复杂的场景,我使用 counter。
解决方案确实是 O(2^n)
For not-so-complex scenario, I use counter.
The solution is indeed O(2^n)