C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了字符串的C递归置换算法 – >不跳过重复大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我很难找到一个简单的语句来跳过这个递归排列代码的重复项.我到处看,似乎只找到使用swap或 java的例子.从我收集的内容来看,我认为我需要在for-loop之后放一条线.

谢谢!

#include "genlib.h"
#include "simpio.h"
#include <String>
#include <iostream>

void ListPermutations(String prefix,String rest);


int main() {

    cout << "Enter some letters to list permutations: ";
    String str = GetLine();
    cout << endl << "The permutations are: " << endl;
    ListPermutations("",str);

    return 0;
}

void ListPermutations(String prefix,String rest)
{
    if (rest == "") 
    {
        cout << prefix << endl;
    } 
    else 
    {   
        for (int i = 0; i < rest.length(); i++) 
        {
            if (prefix != "" && !prefix[i]) conTinue; // <--- I tried adding this,but it doesn't work
            cout << endl<< "prefix: " << prefix << " | rest: " << rest << endl;     
            String newPrefix = prefix + rest[i];
            String newRest = rest.substr(0,i) + rest.substr(i+1);  
            ListPermutations(newPrefix,newRest);           
        }    
    }
}

解决方法

这应该工作:
你的算法是好的,我只添加一个测试:如果一个位置已经使用了一个独特的字符.如果是,则不再进行排列,因为已经在该位置使用该字符的所有排列.

void ListPermutations(String prefix,String rest)
{
if (rest == "") 
{
    cout << prefix << endl;
} 
else 
{   
    for (int i = 0; i < rest.length(); i++) 
    {


        //test if rest[i] is unique.
        bool found = false;
        for (int j = 0; j < i; j++) 
        {
            if (rest[j] == rest[i])
                found = true;
        }
        if(found)
            conTinue;
        String newPrefix = prefix + rest[i];
        String newRest = rest.substr(0,i) + rest.substr(i+1);  
        ListPermutations(newPrefix,newRest);           
    }    
}
}

您也可以在进行排列之前对字符串进行排序,结果将是相同的.

大佬总结

以上是大佬教程为你收集整理的字符串的C递归置换算法 – >不跳过重复全部内容,希望文章能够帮你解决字符串的C递归置换算法 – >不跳过重复所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。