I have two algorithms to compute power set (all subsets) of a set.
For example, {1, 2, 3} => power set is {}, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}
One algorithm is using iterative solution; i (outer for loop) runs for the nums arrays and j runs for all subsets computed so far and keeps adding ith number to previously computed subsets.
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;
}
So given this, I'd like to make sure that I am analyzing the running time correctly. Let's say n is the size of nums array then the outer for-loop is O(n). Inner for loop grows exponentially doubled the size each i iteration thus the inner loop is O(2^n). The final complexity is O(n*2^n). Is this slower than the below recursive solution which is 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);
}