Java 递归函数的空间复杂度估计
我在学习算法和数据结构,现在我在学习时间和空间复杂性 我必须解决一个问题,然后告诉他们(基于我的代码)时间和空间的复杂性 代码如下:Java 递归函数的空间复杂度估计,java,algorithm,Java,Algorithm,我在学习算法和数据结构,现在我在学习时间和空间复杂性 我必须解决一个问题,然后告诉他们(基于我的代码)时间和空间的复杂性 代码如下: public class B { public static int minSum = -1; public static void main(String[] args) { int objects, sumA = 0, sumB = 0; Scanner readInput = new Scanner(Sy
public class B {
public static int minSum = -1;
public static void main(String[] args) {
int objects, sumA = 0, sumB = 0;
Scanner readInput = new Scanner(System.in);
objects = readInput.nextInt();
int[] trunk = new int[objects];
if (objects == 0) {
System.out.print(0 + "\n");
} else if (objects == 1) {
trunk[0] = readInput.nextInt();
System.out.print(trunk[0] + "\n");
} else {
for (int i = 0; i < objects; i++) {
trunk[i] = readInput.nextInt();
}
bruteforce(trunk, sumA, sumB, 0);
System.out.println(minSum);
}
}
public static void bruteforce(int[] trunk, int sumA, int sumB, int index) {
int partialDiff;
if (minSum == 0) {
System.out.println(minSum);
System.exit(0);
} else if (index == trunk.length) {
partialDiff = Math.abs(sumA - sumB);
if (partialDiff < minSum || minSum == -1) {
minSum = partialDiff;
}
} else {
bruteforce(trunk, sumA + trunk[index], sumB, index + 1);
bruteforce(trunk, sumA, sumB + trunk[index], index + 1);
}
}
}
公共B类{
公共静态int minSum=-1;
公共静态void main(字符串[]args){
int对象,sumA=0,sumB=0;
扫描仪读取输入=新扫描仪(System.in);
objects=readInput.nextInt();
int[]trunk=新的int[对象];
如果(对象==0){
系统输出打印(0+“\n”);
}else if(objects==1){
trunk[0]=readInput.nextInt();
系统输出打印(主干[0]+“\n”);
}否则{
for(int i=0;i
基本上,用户首先输入多个对象,然后为每个对象输入其值。该算法将按两个袋子分配对象,并且必须计算按两个袋子分配对象时可以计算的最小差值
我相信这需要指数时间,但我正在努力估算空间复杂性。你能给我指个方向吗?空间复杂度是线性的-
O(n)
计算方法是将每个函数调用中使用的内存量乘以最大递归深度
在每个函数调用中使用的内存量是恒定的-只是partialDiff
和堆栈信息
要确定最大递归深度,基本上只需查看索引
(因为这是决定何时停止更深递归的变量)
- 调用索引为0的函数
- 在每次递归调用中,
增加1索引
- 只要
达到数组的大小,它就会停止索引
bruteforce
的第一次调用,因此一次只有一次会占用内存
因此,对于长度为2的数组,它是这样的:(call1
是第一个函数调用,call2
是第二个函数调用)
因此,最大深度(以及空间复杂度)是3,比数组中的项数多1
因此,它是每个函数调用中使用的
内存*max depth=constant*linear=linear
Sweet。非常感谢。我只是想澄清一下。这是O(2^n)的时间复杂性,不是吗?是的,我相信是这样,每个函数调用都会创建2个分支,因此最终会有2^n个分支,因此是O(2^n)。谢谢您的解释
Call with index 0
Call 1 with index 1
Call 1 with index 2
Call 2 with index 2
Call 2 with index 1
Call 1 with index 2
Call 2 with index 2