-1

I need to generate all permutations for a list of numbers. List of numbers will be from 1 to n. Also the size of permutation can be 1 to m. So if given n=4, m=3, i need to have permutations:

111
112
113
114
121
122
123
124
131
132
133
134
142
142
143
144
211.....

and so on..

Also which of recursion/iteration should be used and why ?

CodeMonkey
  • 2,265
  • 9
  • 48
  • 94
  • This is not a permutation - a permutation has no repeats. Also - it is pretty much a private case of [this thread](http://stackoverflow.com/questions/10149523/generate-a-combination-of-numbers) – amit Sep 22 '12 at 07:40
  • no attempt yet.. i have no clue :( – CodeMonkey Sep 22 '12 at 07:41
  • 1
    @V.J. - sorry, but you are going to have to make an attempt yourself first. If you truly haven't got a clue, there is little point us providing you with an answer that you won't understand. – Stephen C Sep 22 '12 at 08:04
  • 1
    Not to mention that searching for "Java permutation numbers" on SO returns quite a few promising leads... – Mathias Sep 22 '12 at 08:30

1 Answers1

0

Here is an algorithm which return next permutation from previous one in lexical order:

  1. Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.
  2. Find the largest index l such that a[k] < a[l]. Since k + 1 is such an index, l is well defined and satisfies k < l.
  3. Swap a[k] with a[l].
  4. Reverse the sequence from a[k + 1] up to and including the final element a[n].

Try to implement it.

ceth
  • 44,198
  • 62
  • 180
  • 289