流水依依

希望朋友们有个好的身体,开开心心工作与学习。

博客园 首页 新随笔 联系 订阅 管理

题目1369:字符串的排列

时间限制:1 秒

内存限制:32 兆

题目描述:

 

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

 

 

输入:

 

每个测试案例包括1行。

输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

 

 

 

输出:

对应每组数据,按字典序输出所有排列。

 

 

 

 

样例输入:
abc
BCA
样例输出:
abc
acb
bac
bca
cab
cba
ABC
ACB
BAC
BCA
CAB
CBA

打印全排列的算法,思想只有一点,对于当前的一位上添加最小的数。挺经典长考的面试题,一定要注意这些个算法。

#include <iostream>
#include <stdio.h>
#include <queue>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <queue>
#include <set>
#include <algorithm>
#include <map>
#include <stack>
#include <math.h>
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
using namespace std ;
typedef long long LL ;
map<char ,int>mp ;
char ch[10] ;
int used[10] ;
int now[10] ;
int id ,Len;
void dfs(int selc){
    if(selc==Len){
        for(int i=0;i<selc;i++)
            putchar(ch[now[i]]) ;
        puts("") ;
    }
    for(int i=1;i<=id;i++){
        if(used[i]){
            now[selc]=i ;
            used[i]-- ;
            dfs(selc+1) ;
            used[i]++ ;
        }
    }
}
int main(){
  char s[10] ;
  while(scanf("%s",s)!=EOF){
      mp.clear() ;
      Len=strlen(s) ;
      sort(s,s+Len) ;
      id=0 ;
      memset(used,0,sizeof(used)) ;
      for(int i=0;i<Len;i++){
           if(mp.find(s[i])==mp.end()){
               id++ ;
               mp[s[i]] = id ;
               ch[id] = s[i] ;
               used[id]++ ;
           }
           else
               used[mp[s[i]]]++ ;
      }
      dfs(0) ;
  }
  return 0 ;
}

 

posted on 2013-10-17 17:54  流水依依  阅读(256)  评论(0编辑  收藏  举报