|
// ============================================================================
// File: EnhPerRe.cpp - Testing RecPermutation
// Author: Zuoliu Ding, May 2004
// ============================================================================
#include <string>
#include <vector>
using namespace std;
// ============================================================================
// Function: RecPermutation - Enhanced Permutation Recursion
// Description: Generate all Permuted strings for an input string
// Parameter: sz: [in] an input string.
// bRepeated: [in] Allow element repeated or not
// Return: A vector of all Permuted strings.
// ============================================================================
vector<string> RecPermutation(const char* sz,
bool bRepeated)
{
vector<string> v, v1;
string s1; char ch;
int nLen = strlen(sz);
if (nLen==1) // Base case: Add one-char string
v.insert(v.end(), sz);
else // nLen > 1, need recursion
{
for (int i=0; i<nLen; i++)
{
ch = sz[i]; // Extract each char as the first
// To exclude repeated element
if (!bRepeated)
{
for (int j=0; j<i; j++)
if (ch==sz[j]) break;
if (j<i) continue; // If i==j, Not a repeated one
}
s1 = sz; // Copy the original string
s1.erase(i, 1); // Put the rest string into s1
v1 = RecPermutation(s1.c_str(),
bRepeated); // Recursive
for (int i=0; i < (int)v1.size(); i++)
{
s1 = ch + v1[i];
v.insert(v.end(), s1);
}
}
}
return v;
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.