已知一个字符串,输出它包含字符的所有排列(permutations)

原文地址:Write a program to print all permutations of a given string

排列,也叫“排列数”或者“order”(这个咋译?),它是一个有序的列表S一对一下相关的。一个长度为n的字符串有n!种排序。

下面是字符串“ABC”的排列:
ABC ACB BAC BCA CBA CAB

这里有一个基本的回溯方法可作为答案。


这里写图片描述

// C program to print all permutations with duplicates allowed
#include <stdio.h>
#include <string.h>

/* Function to swap values at two pointers */
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

/* Function to print permutations of string
   This function takes three parameters:
   1. String
   2. Starting index of the string
   3. Ending index of the string. */
void permute(char *a, int l, int r)
{
   int i;
   if (l == r)
     printf("%s\n", a);
   else
   {
       for (i = l; i <= r; i++)
       {
          swap((a+l), (a+i));
          permute(a, l+1, r);
          swap((a+l), (a+i)); //backtrack
       }
   }
}

/* Driver program to test above functions */
int main()
{
    char str[] = "ABC";
    int n = strlen(str);
    permute(str, 0, n-1);
    return 0;
}

输出:

ABC
ACB
BAC
BCA
CBA
CAB

算法范式(Paradigm):回溯
时间复杂度: O(n*n!)。注意,这里需要O(n)的时间来打印n!个排列。
注意:如果输入字符串中有重复字符的话,上述方法会打印出相同的排列。如果输入字符串中有相同的字符,但是输出的排列中没有相同的排列,这种问题怎么解决,请看下面的链接:

打印有重复字符的字符串的所有不同排列

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值