Following is the code to calculate subsets of a given array:
Bit Manipulation Method: How to analyse it?
vector<vector<int>> subsets(vector<int>& nums) { sort(nums.begin(), nums.end()); int num_subset = pow(2, nums.size()); vector<vector<int> > res(num_subset, vector<int>()); for (int i = 0; i < nums.size(); i++) for (int j = 0; j < num_subset; j++) if ((j >> i) & 1) res[j].push_back(nums[i]); return res; }
Backtracking Method: How to analyse it
vector<vector<int>> subsets(vector<int>& nums) { sort(nums.begin(), nums.end()); // sort the original array vector<vector<int>> subs; vector<int> sub; genSubsets(nums, 0, sub, subs); return subs; } void genSubsets(vector<int>& nums, int start, vector<int>& sub,vector<vector<int>>& subs) { subs.push_back(sub); for (int i = start; i < nums.size(); i++) { sub.push_back(nums[i]); genSubsets(nums, i + 1, sub, subs); sub.pop_back(); } }
Vector operations: -
push_back
andpop_back
are bothO(1)
- Constructor with size argumentn
isO(n)
Bit manipulation method:
sort
isO(n log n)
res
isO(nums_subset) = O(2^n)
Outer loop is executed
n
times, inner bynums_subset = 2^n
times.Backtracking method:
sort
isO(n log n)
Each
genSubsets
call loops throughnums.size() - start
times, each time performing a recursive call with 1 less loop.Which is bigger? By Stirling's approximation,
So Backtracking is more costly.