Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created December 9, 2018 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkphp/c7de2cc6ceda3e29aede0818b27f2631 to your computer and use it in GitHub Desktop.
Save thinkphp/c7de2cc6ceda3e29aede0818b27f2631 to your computer and use it in GitHub Desktop.
backtracking in ruby. display the perm
@n = 3
@stack = [0]*(@n)
def valid(level)
for i in 1..level-1
if @stack[i] == @stack[level]
return 0
end
end
return 1
end
def display
for i in 1..@n
print @stack[i].to_s + " "
end
print "\n"
end
def bk(level)
for i in 1..@n
@stack[level] = i
if valid(level) == 1
if level == @n
display
else
bk(level+1)
end
end
end
end
bk(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment