careercup-Recursive and dynamic programming 9.5

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.