字符串的全排列

题目:输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a、b、c所能排列出来的所有字符串abc,acb, bac, bca, cab, cba。

C++版本

#include <iostream>
#include <string.h>
using namespace std;

template<typename T>
void swap_interview(T& a, T& b) {
	T temp;
	temp = a;
	a = b;
	b = temp;
}

char s[10] = { '0' };
void permutation(string ch, int begin, int end) {
	//cout << "begin:" << begin << " end:" << end << endl;
	if (begin + 1 == end) {
		/* 输出当前的排列 */
		for (int i = 0; i < end; i++)
		{
			//printf("%d ", ch[i]);
			cout << ch[i];
		}
		cout << endl;
	}
		
	else {
		int aa(0);
		for ( (aa = begin); aa < end; ++aa) {
			//cout << "aa:" << aa << endl;
			swap_interview(ch[begin], ch[aa]);
			//cout  << ch[begin] << " ";
			permutation(ch, begin + 1, end);
                        // 将改变过的字符串恢复为原始字符串,以便于下一次循环迭代是基于原始字符串开始的
			swap_interview(ch[begin], ch[aa]);
			
		}
	}
}

void f(int a) {
	for (int i = a; i < 5; ++i)
	{
		cout << "a:" << a << endl;
		cout << "i:" << i << endl;
	}
}


int main(void)
{
	string ch("abc");
	//ch[0] = 'c';
	//return ch[0];
	cout << "ch size:" << ch.size() << endl;
	permutation(ch, 0, ch.size());
	//f(0);

	return 0;
}

自己写出的错误版本:


教训:

DFS还需要练习,多写几遍

书中给出的C语言版本:

// StringPermutation.cpp : Defines the entry point for the console application.
//

// 《剑指Offer——名企面试官精讲典型编程题》代码
// 著作权所有者:何海涛

#include "stdafx.h"

void Permutation(char* pStr, char* pBegin);

void Permutation(char* pStr)
{
    if(pStr == NULL)
        return;

    Permutation(pStr, pStr);
}

void Permutation(char* pStr, char* pBegin)
{
    if(*pBegin == '')
    {
        printf("%s
", pStr);
    }
    else
    {
        for(char* pCh = pBegin; *pCh != ''; ++ pCh)
        {
            char temp = *pCh;
            *pCh = *pBegin;
            *pBegin = temp;

            Permutation(pStr, pBegin + 1);

            temp = *pCh;
            *pCh = *pBegin;
            *pBegin = temp;
        }
    }
}

// ====================测试代码====================
void Test(char* pStr)
{
    if(pStr == NULL)
        printf("Test for NULL begins:
");
    else
        printf("Test for %s begins:
", pStr);

    Permutation(pStr);

    printf("
");
}

int _tmain(int argc, _TCHAR* argv[])
{
    Test(NULL);

    char string1[] = "";
    Test(string1);

    char string2[] = "a";
    Test(string2);

    char string3[] = "ab";
    Test(string3);

    char string4[] = "abc";
    Test(string4);

    return 0;
}

ref:
《剑指offer》何海涛
https://blog.csdn.net/u010889616/article/details/48165689

转载本Blog文章请注明出处,否则,本作者保留追究其法律责任的权利。 本人转载别人或者copy别人的博客内容的部分,会尽量附上原文出处,仅供学习交流之用,如有侵权,联系立删。
原文地址:https://www.cnblogs.com/drfxiaoliuzi/p/9279091.html