题目描述
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
注意
Note: The solution set must not contain duplicate subsets.
Example:
Input: [1,2,2]Output:[[2],[1],[1,2,2],[2,2],[1,2],[]]
题目解读:
找出所有的子集。思路:确定子集的来源, 遍历原始列表,每一个元素都往已有的子集列表里边添加,同时添加到已有的子集中去,产生新的子集。类似于动态规划思想,依赖于之前的东西产生现在的东西。
class Solution: # @param num, a list of integer # @return a list of lists of integer def subsetsWithDup(self, S): res = [[]] S.sort() for i in range(len(S)): if i==0 or S[i]!=S[i-1]: l=len(res) for j in range(len(res)-l,len(res)): res.append(res[j]+[S[i]]) return resif __name__=='__main__': st=Solution() S=[1,2,2] S=[0] result=st.subsetsWithDup(S)