3

It's more a math problem I guess, nothing programming.

Suppose I have a stack and I want to find the permutations of numbers 1,2,3,...n. I can push and pop. e.g. if n=2: push,pop,push,pop 1,2 and push,push,pop,pop 2,1

if n=4 I can only get 14 from the 24 permutations using the stack.. Does anyone know any function F(n) that could produce the number of permutations the stack (only one) can produce? eg f(1)=1

f(2)=2

f(4)=14

Guy Coder
  • 24,501
  • 8
  • 71
  • 136
alhid
  • 61
  • 2

2 Answers2

3

Such function is a Catalan number. See http://en.wikipedia.org/wiki/Catalan_number for the formula.

konrad.kruczynski
  • 46,413
  • 6
  • 36
  • 47
  • Yes, this is the correct answer. Didn't know about those, but looking at the "Applications in combinatorics" section, this is exactly what we want here. – schnaader Jan 16 '11 at 20:12
0

I think there is some quite easy formula for that. You're looking for permutations of N push operations ("X") and N pop ("Y") operations, following one simple rule:

  • No pop on an empty stack (f.e. Y.... and XXYYY... are invalid)

Perhaps some recursive definition helps:

function F(n_push, n_pop) {
  int total_count = 0;

  if (n_push > 0) total_count += F(n_push - 1, n_pop);
  if (n_pop > n_push) total_count += F(n_push, n_pop - 1);

  return total_count;
}
schnaader
  • 49,103
  • 10
  • 104
  • 136
  • Thank you very much!! Very nice. I was looking something more close to mathematical terms though. I really appreciate for helping. – alhid Jan 16 '11 at 20:14