|
| 1 | +class Solution(object): |
| 2 | + # def subsets(self, nums): |
| 3 | + # """ |
| 4 | + # :type nums: List[int] |
| 5 | + # :rtype: List[List[int]] |
| 6 | + # """ |
| 7 | + # nums.sort() |
| 8 | + # res = [[]] |
| 9 | + # res.append(list(nums)) |
| 10 | + # for ls in range(1, len(nums)): |
| 11 | + # self.get_subsets(res, nums, [], ls, 0) |
| 12 | + # return res |
| 13 | + # |
| 14 | + # def get_subsets(self, res, nums, curr_set, ls, index): |
| 15 | + # # recursive |
| 16 | + # if ls == 0: |
| 17 | + # res.append(list(curr_set)) |
| 18 | + # elif index < len(nums): |
| 19 | + # curr_set.append(nums[index]) |
| 20 | + # self.get_subsets(res, nums, curr_set, ls - 1, index + 1) |
| 21 | + # curr_set.pop() |
| 22 | + # self.get_subsets(res, nums, curr_set, ls, index + 1) |
| 23 | + |
| 24 | + # def subsets(self, nums): |
| 25 | + # # https://leetcode.com/discuss/89343/c-8-lines-bit-operation |
| 26 | + # # doesn't work when len(nums) > 32 |
| 27 | + # nums.sort() |
| 28 | + # res = [] |
| 29 | + # for i in range(1 << len(nums)): |
| 30 | + # res.append(self.get_subsets(nums, i)) |
| 31 | + # return res |
| 32 | + # |
| 33 | + # def get_subsets(self, nums, magic): |
| 34 | + # res = [] |
| 35 | + # for i in range(len(nums)): |
| 36 | + # if (1 << i) & magic != 0: |
| 37 | + # res.append(nums[i]) |
| 38 | + # return res |
| 39 | + |
| 40 | + def subsets(self, nums): |
| 41 | + # Sort and iteratively generate n subset with n-1 subset, O(n^2) and O(2^n) |
| 42 | + nums.sort() |
| 43 | + res = [[]] |
| 44 | + for index in range(len(nums)): |
| 45 | + size = len(res) |
| 46 | + # use existing subsets to generate new subsets |
| 47 | + for j in range(size): |
| 48 | + curr = list(res[j]) |
| 49 | + curr.append(nums[index]) |
| 50 | + res.append(curr) |
| 51 | + return res |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + s = Solution() |
| 58 | + print s.subsets([1,2,3]) |
0 commit comments