【问题标题】:compute power set algorithm analysis算力集算法分析
【发布时间】:2017-07-15 22:45:27
【问题描述】:

我有两种算法来计算集合的幂集(所有子集)。 例如{1, 2, 3} => 幂集是{}, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}

一种算法正在使用迭代解决方案; i(外部 for 循环)运行 nums 数组和 j 运行到目前为止计算的所有子集,并不断将 ith 数字添加到先前计算的子集。

static List<List<Integer>> subsetItr(int[] nums) {
    List<List<Integer>> subsets = new LinkedList<>();
    subsets.add(new LinkedList<>());
    for (int i = 0; i < nums.length; i++) {
        int size = subsets.size();
        for (int j = 0; j < size; j++) {
            List<Integer> current = new LinkedList<>(subsets.get(j));
            current.add(nums[i]);
            subsets.add(current);
        }
    }
    return subsets;
}

因此,鉴于此,我想确保我正在正确分析运行时间。假设 n 是 nums 数组的大小,那么外部 for 循环是 O(n)。内部 for 循环以指数方式增长,每次 i 迭代的大小增加一倍,因此内部循环为O(2^n)。最终复杂度为O(n*2^n)。这比下面的递归解决方案O(2^n) 慢吗?

static List<List<Integer>> subsets(int[] nums) {
    List<Integer> current = new LinkedList<>();
    _subsets(nums, 0, current, ret);
    return ret;
}

static void _subsets(int[] nums, int pos, List<Integer> current) {
    if (pos == nums.length) {
        System.out.println(current);
        return;
    }
    current.add(nums[pos]);
    _subsets(nums, pos + 1, current, ret);
    current.remove(current.size() - 1);
    _subsets(nums, pos + 1, current, ret);
}

【问题讨论】:

  • 你试过测量吗?
  • 我做了..如果我真的运行程序,那么迭代解决方案需要更长的时间,但我想确保我的运行时分析是正确的。尽管根据下面的答案,我对迭代解决方案的分析似乎是不正确的。

标签: algorithm


【解决方案1】:

它们是相同的,两者的复杂度都是 O(2^n),因为你的第一个算法的复杂度是 O(1+2+2^2+...+2^(n-1))=O (2^n),你不能把内循环的所有复杂度都看成一样,你必须分别计算,然后像我一样将它们全部相加,希望这篇文章对你有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-28
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 2014-10-28
    相关资源
    最近更新 更多