本文主要是介绍leetcode78. Subsets,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
思路:状态压缩(话说这b装的膝盖一跪)
学过数电,就是枚举
[1,2,3]
————
0 0 0 []
0 0 1 [3]
0 1 0 [2]
0 1 1 [2,3]
1 0 0 [1]
1 0 1 [1,3]
1 1 0 [1,2]
1 1 1 [1,2,3]
class Solution(object):def subsets(self, nums):""":type nums: List[int]:rtype: List[List[int]]"""ret=[]if not len(nums):return retfor i in range(2**(len(nums))):tmp=[]state=list('{:b}'.format(i)) #10进制转2进制state=['0']*(len(nums)-len(state))+statefor j in range(len(state)):if state[j]=='1':tmp.append(nums[j])ret.append(tmp)return ret
这篇关于leetcode78. Subsets的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!