Skip to content

Commit

Permalink
46
Browse files Browse the repository at this point in the history
  • Loading branch information
ACEMerlin committed Apr 22, 2019
1 parent a388b14 commit b2a76af
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions 46.permutations.rb
Expand Up @@ -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.