472 ms Ruby AC Solution. How to improve?


  • 2
    def subsets(nums)
      sub([nums.sort],0)
    end
    
    def sub(ans,start=0)
      t = ans.length
      (start...t).each {|i| ans[i].each {|x| ans << ans[i] - [x] if not ans.include?(ans[i] - [x])}}
      return ans if ans[-1].empty?
      sub(ans,t)
    end

  • 0
    N

    the recursion is beautiful! I would only suggest

    1. making loops to look not so condensed;

    2. using unless instead of "if not".
      However, this is a matter of taste.

      def subsets(nums)
      sub([nums.sort],0)
      end

      def sub(ans,start)
      t = ans.length
      (start...t).each do |i|
      ans[i].each do |x| ans << ans[i] - [x] unless ans.include?(ans[i] - [x])
      end
      end
      return ans if ans[-1].empty?
      sub(ans,t)
      end


Log in to reply
 

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