9.5 Write a method that determines all permutation combinations of a string.
Similar leetcode:permutations
Solution:
As with many recursive problems, the simple construction method works very well. Suppose there is a string s, expressed as a sequence of characters a1a2a...an.
Termination Condition: N=1
S=A1, there is only one permutation combination, that is, the string A1
Situation: n=2
S=A1A2 There are two permutations of A1A2 and A2A1
Situation: N
For the general case, we just need to repeat this step. That is, the solution of F (n-1) has been obtained, and then as long as the an is inserted into any position of these strings.
C + + code implementation:
#include <iostream>#include<vector>#include<string>using namespaceStd;vector<string> getperms (stringstr) { if(Str.empty ())returnvector<string>(); intn=str.length (); Vector<string>Res; Res.push_back (string("")); Vector<string>R; inti,j; for(i=0; i<n;i++) { CharC=Str[i]; R=Res; Res.clear (); for(j=0; J<r.size (); j + +) { stringtmp=R[j]; intindex=0; while(Tmp.begin () +index!=Tmp.end ()) {Tmp.insert (Tmp.begin ()+index,c); Res.push_back (TMP); TMP=R[j]; Index++; } tmp.push_back (c); Res.push_back (TMP); } } returnRes;}intMain () {stringStr="ABC"; Vector<string> res=getperms (str); for(auto s:res) cout<<s<<Endl;}
careercup-Recursive and dynamic programming 9.5