小编Pat*_*tes的帖子

降低o(n ^ 3)c ++代码的复杂性

我想降低以下算法的复杂性.基本上,它需要一个单词作为输入并计算其中的唯一字母数(单词的"熵").我目前的解决方案采用3个嵌入式for循环,其复杂度为o(n ^ 3).由于此代码是更大项目的一部分(我们为游戏构建了一个称为boggle的解算器),我希望降低算法的复杂性,以减少其执行时间.提前致谢!

int wordEntropy(string word)
{

int length = word.length();
int uniquewords = length;
string compare = word;
char save[17];
int cond=0;

for (int ii=0; ii < length; ii++)
{

    for (int jj=ii+1; jj < length; jj++)
    {
        for (int kk=0; kk<= ii; kk++)
        {
            if (save[kk] == word[ii]) {cond++;}
        }
        if (word[ii] == word[jj])
        {
            if (cond>0) {break;}
            uniquewords--;
        }
    }

    save[ii] = word[ii];
    cond = 0;

}
return uniquewords;
}
Run Code Online (Sandbox Code Playgroud)

c++ algorithm performance for-loop code-complexity

5
推荐指数
3
解决办法
681
查看次数

标签 统计

algorithm ×1

c++ ×1

code-complexity ×1

for-loop ×1

performance ×1