Write a method to compute all permutations of a string.
// =====================================================================================
//
// Filename: 8_4.cpp
//
// Description: a method to compute all permutations of a string
//
// Version: 1.0
// Created: 03/21/2016 09:53:33 AM
// Revision: none
// Compiler: g++
//
// Author:
// Organization:
//
// =====================================================================================
#include <iostream>
#include <string>
#include <list>
void permutations(const std::string& prefix,const std::string& str, std::list<std::string>& str_list){
if(str.empty())
{
str_list.push_back(prefix);
return;
}
for(int i=0; i<str.size(); i++){
std::string str_tmp(str);
std::string prefix_tmp(prefix);
if(str.find_first_of(str[i])!=i) continue;
permutations(prefix_tmp.append(1, str[i]), str_tmp.erase(i,1), str_list);
}
}
std::list<std::string> permutations(const std::string& str){
std::list<std::string> str_list;
permutations("", str, str_list);
return str_list;
}
// === FUNCTION ======================================================================
// Name: main
// Description:
// =====================================================================================
int main ( int argc, char *argv[] )
{
std::list<std::string> str_list = permutations("1224");
std::cout << str_list.size() << std::endl;
for(auto it = str_list.begin(); it!=str_list.end(); it++){
std::cout << *it << std::endl;
}
return 0;
} // ---------- end of function main ----------