【问题标题】:Does return value account for space complexity返回值是否考虑了空间复杂度
【发布时间】:2014-12-05 04:56:42
【问题描述】:

以下是用于生成多个集合的算法。正好解决了下面的问题Print all combination of element in the array such that first element of array is d and next element in the array can be +1 or -1 the previous element in the array. Code was required. Input: num=4, level=3. Output - 4, 3, 2 || 4, 3, 4 || 4, 5, 4 || 4, 5, 6

这个问题没有使用 int[] arr = new int[level] 作为数据存储,它最终被复制到一个 int 数组列表中。

以下代码的空间复杂度是多少?是 O(level) 即用于解决问题的存储还是 O(2^level - 1) 即返回类型的大小?

public static List<int[]> getCombinations(int num, int level) {
        final List<int[]> combinations = new ArrayList<int[]>();
        int[] arr = new int[level]; 
        computeCombinations(num, level - 1, 0, combinations, arr);  // note : its level - 1, since currentlevel is set to 0.
        return combinations;
    }


    private static void computeCombinations(int num, int level, int currLevel, List<int[]> list, int[] arr) {
        arr[currLevel] = num;

        if (currLevel == level) {
            // list.add(arr);  <- wrong to do it so
            int[] temp = new int[arr.length];
            System.arraycopy(arr, 0, temp, 0, arr.length);
            list.add(temp);
            return;
        }

        computeCombinations(num - 1, level, currLevel + 1, list, arr);
        computeCombinations(num + 1, level, currLevel + 1, list, arr);
    }

【问题讨论】:

  • 我会说O(level * 2^(level-1)),因为代码显然会在内存中生成整个列表。

标签: java algorithm complexity-theory space-complexity


【解决方案1】:

空间复杂度占算法使用的实时内存量,因此ArrayList&lt;int[]&gt; 是复杂度的因素。但是,您帖子顶部给出的算法描述说您只需要打印组合,而不是返回它们;如果您在创建组合后立即打印出组合然后丢弃它们(即破坏性地更新组合而不是复制组合),那么您将提高空间复杂度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 2012-08-14
    相关资源
    最近更新 更多