c++ - Recursion to generate permutations -
i find recursion, apart straight forward ones factorial, difficult understand. if want print permutations of string, lets string length 5, "abcde"
, permutations of length 7 should be
abced abdce abdec abecd abedc acbde acbed acdbe acdeb acebd acedb adbce adbec adcbe adceb adebc adecb aebcd aebdc aecbd aecdb aedbc aedcb bacde baced badce badec baecd baedc bcade bcaed ...
if want recursion calculate permutation of factorial of 5
, 4
, 3
, 2
or 1
. algorithm should use? there function in c++ library this?
assume printout should this:
acbd bcad abc bac ab ba
using recursion algorithm, pretty mathematical induction. first need deal base case, , find sub-problem pattern.
for factorial, define problem f(n)
factorial of n
.
- base case,
f(0)=1
- sub-problem pattern,
f(n)=n!=n*(n-1)!=n*f(n-1)
and permutations, define p(e)
permutation of set e
.
- base case,
p({}) = {{}}
- sub-problem pattern. consider process of permutation, let's have chosen first element
x
, got sub-problem,p(e-x)
, eachp in p(e-x)
, ,x
front, got permutations starting elementx
, iteratex
got permutations, akap(e)
.
in c++, can use next_permutation
.
and example code above thought like:
// generate permutation of {a[st], a[st+1], ..., a[ed]} void p(char a[], int st, int ed) { if (st > ed) { puts(a); return; } // nothing generate (int i=st; i<=ed; ++i) { swap(a[st], a[i]); // enumerate first element p(a, st+1, ed); swap(a[st], a[i]); // recover } }
check on http://ideone.com/zbawy2.
Comments
Post a Comment