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.

  1. base case, f(0)=1
  2. sub-problem pattern, f(n)=n!=n*(n-1)!=n*f(n-1)

and permutations, define p(e) permutation of set e.

  1. base case, p({}) = {{}}
  2. sub-problem pattern. consider process of permutation, let's have chosen first element x, got sub-problem, p(e-x), each p in p(e-x), , x front, got permutations starting element x, iterate x got permutations, aka p(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

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -