5. 字符串的全排列

    实现一个函数,打印出一个字符串中字符的所有可能顺序。换言之,就是打印出原来字符串中所有字符的全排列。例如,对于字符串“hat”,函数应该打印出字符串“tha”,“aht”,“tah”,“ath”,“hta”,“hat”。将输入字符串中的每个字符作为一个独立的字符,即使它们发生重复。对于字符串“aaa”,函数应该打印出6个“aaa”。可以按任何顺序打印出全排列。

    程序的代码如下:

    #include "stdafx.h"

    #include <iostream.h>

    #include <string.h>

    #include <stdio.h>

    #include <stdlib.h>

 

    void DoPermute(char in[], char out[], int used[], int length, int recurslev)

    {

        int i;

  

        // Base case

        if(recurslev == length)

        {

            printf("%s/n", out); // Print permutation

            return;

        }

 

        // Recursive case

        for(i = 0; i < length; i++)

        {

            if(used[i]) // if used, skip to next letter

                continue;

 

            out[recurslev] = in[i]; // Put current letter in output

            used[i] = 1;

            DoPermute(in, out, used, length, recurslev + 1);

            used[i] = 0;

        }

    }

 

    int Permute(char inString[])

    {

        int length, i, *used;

        char *out;

 

        length = strlen(inString);

        out = (char*)malloc(length + 1);

        if(!out) // Failed

            return 0;

 

        // So printf doesn't run past the end of the buffer

        out[length] = '/0';

        used = (int*)malloc(sizeof(int) * length);

        if(!used) // Failed

            return 0;

 

        // Start with no letters used, so zero array

        for(i = 0; i < length; i++)

        {

            used[i] = 0;

        }

 

        DoPermute(inString, out, used, length, 0);

 

        free(out);

        free(used);

        return 1; // Success

    }

 

    int main()

    {

        char str[] = "hat";

      

        Permute(str);

 

        return 0;

    }

 

    // 程序的执行结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值