编程算法

版权声明:本文为博主原创文章。未经博主同意不得转载。

https://blog.csdn.net/u012515223/article/details/35593485

字符串的排列 代码(C)


本文地址: http://blog.csdn.net/caroline_wendy


题目: 输入一个字符串, 打印出该字符串中字符的全部排列.


方法: 使用递归依次交换位置, 打印输出.


代码:

/*
 * main.cpp
 *
 *  Created on: 2014.6.12
 *      Author: Spike
 */

/*eclipse cdt, gcc 4.8.1*/

#include <stdio.h>

void Permutation(char* str, char* begin);

void Permutation(char* str){
    if(str == NULL)
        return;
    Permutation(str, str);
}

void Permutation(char* str, char* begin) {
    if(*begin == '') {
        printf("%s
", str);
        return;
    }

	for (char* c = begin; *c != ''; ++c) {
		char temp = *c;
		*c = *begin;
		*begin = temp;

		Permutation(str, begin + 1);

		temp = *c;
		*c = *begin;
		*begin = temp;
	}

}

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

    Permutation(pStr);

    printf("
");
}

int main(void)
{
    char str[] = "abc";
    Test(str);

    return 0;
}



输出:

Test for abc begins:
abc
acb
bac
bca
cba
cab




【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/ldxsuanfa/p/10502289.html