0

我正在学习算法和数据结构,我现在处于时间和空间复杂性方面。

我必须解决一个问题,然后他们告诉(基于我的代码)时间和空间复杂性。

这是代码:

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);
        }
    }
}

基本上,用户首先输入一些对象,然后为每个对象输入其值。该算法将按两个袋子分配对象,并且必须计算按两个袋子分配对象时可以计算的最小差值。

我相信这需要指数级的时间,但我正在努力估计空间复杂性。你能指点我一些方向吗?

4

1 回答 1

2

空间复杂度是线性的 - O(n)

您可以通过将每个函数调用中使用的内存量乘以最大递归深度来计算此值。

每个函数调用中使用的内存量是恒定的 - 只是partialDiff和堆栈信息。

要确定最大递归深度,您基本上可以只看一下index(因为这是决定何时停止更深递归的变量)。

  • index您使用= 0调用该函数。
  • 在每次递归调用时,index增加一。
  • 一旦index达到数组的大小,它就会停止。

请注意,函数调用是深度优先的,这意味着它将bruteforce在第二次调用之前完全评估第一次调用,因此一次只会占用一个内存。

因此,对于长度为 2 的数组,它是这样的:(Call 1是第一个函数调用,Call 2第二个)

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

所以最大深度(以及空间复杂度)是 3,比数组中的项目数多 1。

所以它是memory used in each function call * max depth = constant * linear = linear

于 2013-05-22T09:22:12.057 回答