Skip to content
Permalink
Browse files

46

  • Loading branch information...
ACEMerlin committed Apr 15, 2019
1 parent a388b14 commit b2a76affb776dc9a407c61211644a027f88bbe4e
Showing with 36 additions and 0 deletions.
  1. +36 −0 46.permutations.rb
@@ -51,3 +51,39 @@ def permute(nums, k=0, ans=[])
def swap(nums, i, j)
nums[i], nums[j] = nums[j], nums[i]
end


# DFS+Backtracking.

def permute(nums, seen=Set.new, path=[], paths=[])
if path.size == nums.size
paths << path.dup
else
nums.each do |n|
next if seen.include?(n)
path << n
seen << n
permute(nums, seen, path, paths)
path.pop
seen.delete(n)
end
end
paths
end


# DFS.

def permute(nums, seen=Set.new, path=[], paths=[])
if path.size == nums.size
paths << path.dup
else
nums.each do |n|
next if seen.include?(n)
seen << n
permute(nums, seen, path+[n], paths)
seen.delete(n)
end
end
paths
end

0 comments on commit b2a76af

Please sign in to comment.
You can’t perform that action at this time.