Simple python code


  • 3
    J
    class Solution:
        # @param S, a list of integer
        # @return a list of lists of integer
        def subsets(self, S):
        	if S == []:
        		return []
            S.sort() #sort the array to avoid descending list of int
            res=[[]]
            for element in S:
            	temp = []
            	for ans in res:
            		 #append the new int to each existing list
            		temp.append(ans+[element])
            	res += temp
            return res

  • 0
    L

    Really nice and concise! Would be better if the idea is explained a little bit.


  • 0
    N

    I've done the same, thank your for sharing you solution!
    Here is same solution in Ruby (mb it will be usefull for someone).

    return [] if nums.empty?
    arr = nums.sort
    result = [[]]
     
    #go through numbers in **arr** to combine these with digits from **result** array
    arr.each do |arr_item|
    
        #temp stores combination of current arr_item with items from **result** array
        temp = [] 
    
        result.each do |result_item|
            temp << [arr_item, result_item].flatten.sort
        end
               result += temp 
    end
    return result

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.