Skip to content

Instantly share code, notes, and snippets.

@meaganewaller
Created July 1, 2013 17:25
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 meaganewaller/5902799 to your computer and use it in GitHub Desktop.
Save meaganewaller/5902799 to your computer and use it in GitHub Desktop.
Eliminating Recursion with Stacks
def base_condition_for_comb(n,m)
(1 == n) || (0 == m) || (m == n)
end
def comb(n,m)
return 1 if base_condition_for_comb(n,m)
stack = [[n,m]]
result = 0
while !stack.empty?
n, m = stack.pop
if base_condition_for_comb(n,m)
result += 1
else
stack.push([n-1, m])
stack.push([n-1, m-1])
end
end
result
end
def base_condition_for_comb(n,m)
(1 == n) || (0 == m) || (m == n)
end
def comb(n,m)
return 1 if base_condition_for_comb(n,m)
stack = [[n,m]]
result = 0
while !stack.empty?
n, m = stack.pop
if base_condition_for_comb(n,m)
result += 1
else
stack.push([n-1, m])
stack.push([n-1, m-1])
end
end
result
end
def comb(n,m)
if (1 == n) || (0 == m) || ( m == n)
return 1
else
return (comb(n-1), m) + comb(n-1, m-1))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment