Simple Iterative Ruby solution


  • 0
    Y
    # @param {Integer[]} nums
    # @return {Integer[][]}
    def permute(nums)
      # iterative solution
      nums[1..-1].each_with_object([[ nums[0] ]]) do |c, perms|
        perms.length.times do |i|
          perm = perms.shift
          # stuff the current element in all possible positions
          for j in 0..perm.length
            perms << perm.dup.insert(j, c)
          end
        end
      end
    end
    

Log in to reply
 

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