问题
This is problem 9.4 from Cracking the Coding Interview 5th
The Problem: Write a method to return all the subsets of a set.
Here is my solution in Java.(tested it, it works!!!)
public static List<Set<Integer>> subsets(Set<Integer> s) {
Queue<Integer> copyToProtectData = new LinkedList<Integer>();
for(int member: s) {
copyToProtectData.add(member);
}
List<Set<Integer>> subsets = new ArrayList<Set<Integer>>();
generateSubsets(copyToProtectData, subsets, new HashSet<Integer>());
return subsets;
}
private static void generateSubsets(Queue<Integer> s,
List<Set<Integer>> subsets, Set<Integer> hashSet) {
if(s.isEmpty()) {
subsets.add(hashSet);
} else {
int member = s.remove();
Set<Integer> copy = new HashSet<Integer>();
for(int i:hashSet) {
copy.add(i);
}
hashSet.add(member);
Queue<Integer> queueCopy = new LinkedList<Integer>();
for(int i:s){
queueCopy.add(i);
}
generateSubsets(s, subsets, hashSet);
generateSubsets(queueCopy, subsets, copy);
}
}
I looked at the solutions for this problem and the author said that the solution to this algorithm runs in O(2n) time complexity and O(2n) space complexity. I agree with her that this algorithm runs in O(2n) time because to solve this problem, you have to consider the fact that for any element, you have two possibilities, it can either be in the set or not. And because you have n elements, your problem will have 2n possibilities so the problem would be solved with O(2n) time.
However I believe that I have a compelling argument that my algorithm runs in O(n) space. I know that space complexity is "the total space taken by an algorithm with respect to the input size" Space Complexity and is relative to the the depth of a recursive call(remember this from some Youtube video I watched)
An example I have is generating [1,2,3] as a subset of [1,2,3]. Here is the set of recursive calls to generate that set
generateSubsets([], subsets, [1,2,3])
generateSubsets([3],subsets,[1,2])
generateSubsets([2,3],subsets,[1])
generateSubsets([1,2,3],subsets,[])
This show that the greatest depth of a recursive call with respect to the original set size n is n itself. Each of these recursive calls will have its own stack frame. So from this, I concluded that the space complexity is O(n) Does anyone see any flaws in my proof?
回答1:
You need to take into account all memory that is allocated by your algorithm (or, rather, the greatest amount of allocated memory that is "in use" at any time) - not only on the stack, but also on the heap. Each of the generated subsets is being stored in the subsets
list, which will eventually contain 2n sets, each of size somewhere between 0 and n (with most of the sets containing around n / 2 elements) - so the space complexity is actually O(n 2n).
来源:https://stackoverflow.com/questions/29225659/is-the-space-complexity-of-this-subset-algorithm-actually-on