Full permutation recursive algorithm

Source: Internet
Author: User

固定第一个字符,递归取得首位后面的各种字符串组合;       * 再把第一个字符与后面每一个字符交换,并同样递归获得首位后面的字符串组合; *递归的出口,就是只剩一个字符的时候,递归的循环过程,就是从每个子串的第二个字符开始依次与第一个字符交换,然后继续处理子串。       *       * 假如有重复值呢?       * *由于全排列就是从第一个数字起,每个数分别与它后面的数字交换,我们先尝试加个这样的判断——如果一个数与后面的数字相同那么这两个数就不交换了。       * 例如abb,第一个数与后面两个数交换得bab,bba。然后abb中第二个数和第三个数相同,就不用交换了。       * 但是对bab,第二个数和第三个数不 同,则需要交换,得到bba。       * 由于这里的bba和开始第一个数与第三个数交换的结果相同了,因此这个方法不行。       *       * 换种思维,对abb,第一个数a与第二个数b交换得到bab,然后考虑第一个数与第三个数交换,此时由于第三个数等于第二个数,       * 所以第一个数就不再用与第三个数交换了。再考虑bab,它的第二个数与第三个数交换可以解决bba。此时全排列生成完毕!
#include <iostream>#include<string.h>using namespacestd;intn=3;intCnt=0;voidSwapintCs[],intIintj) {        inttemp =Cs[i]; Cs[i]=Cs[j]; CS[J]=temp;}voidPermutation (intA[],inti) {    if(i==N) {cout<<++cnt<<":";  for(i=0; i<n;i++) cout<<a[i]<<" "; cout<<Endl; }Else{         for(intj=i;j<n;j++) {swap (A,I,J); Permutation (A,i+1);        Swap (a,j,i); }    }}intMain () {inta[30000],i;  for(i=0; i<n;i++) A[i]=i+1; Permutation (A,0); return 0;}

Http://www.cnblogs.com/cxjchen/p/3932949.html

Full permutation recursive algorithm

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.