l=[] def All(str1): for i in str1: tmp=str1.replace(i,'') l.append(i) if len(tmp)>1: All(tmp) del l[-1] else: print ''.join(l)+tmp del l[-1] All("ABC")
c++版本
#include<iostream> #include<string.h> #include<stdio.h> using namespace std; string result; void CharAllSort(string str) { int len=str.length(); if(len<=0) return; for(int i=0;i<len;i++) { result.append(str.substr(i,1)); string tmp=str; tmp.replace(i,1,""); if(tmp.length()>1) { CharAllSort(tmp); result.replace(result.length()-1,1,""); } else { cout<<result<<tmp<<endl; result.replace(result.length()-1,1,""); } } }