Created
December 9, 2018 11:14
-
-
Save thinkphp/c7de2cc6ceda3e29aede0818b27f2631 to your computer and use it in GitHub Desktop.
backtracking in ruby. display the perm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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