subsets.py 681 B

1234567891011121314151617181920
  1. # Given a set of distinct integers, nums, return all possible subsets.
  2. # This could be solved with backtrack algorithm.
  3. # Time complexity: O(1). Only list is appended (in Python. Because Python allocates
  4. # up to twice of the space as needed)
  5. # Space complexity: O(n^2). Store all the combination of a list with length n
  6. import pytest
  7. def test_subsets():
  8. assert subsets([0,1]) == [[],[0],[0,1],[1]]
  9. def subsets(nums):
  10. def backtrack(list, temp_list, nums,start):
  11. list.append(temp_list)
  12. for i in range(start,len(nums)):
  13. backtrack(list,temp_list+[nums[i]],nums,i+1)
  14. return list
  15. list = []
  16. backtrack(list,[],nums,0)
  17. return list