c++ - 找到数字数组的所有可能的解释

标签 c++ algorithm recursion dynamic-programming

考虑一个字母到整数的编码系统,其中 'a' 表示为 1,'b' 表示为 2,.. 'z' 表示为 26。给定一个数字数组(1 到 9)作为输入,编写一个函数打印输入数组的所有有效解释。

/*Examples

Input: {1, 1}
Output: ("aa", 'k") 
[2 interpretations: aa(1, 1), k(11)]

Input: {1, 2, 1}
Output: ("aba", "au", "la") 
[3 interpretations: aba(1,2,1), au(1,21), la(12,1)]

Input: {9, 1, 8}
Output: {"iah", "ir"} 
[2 interpretations: iah(9,1,8), ir(9,18)]*/

我的c代码

#include<iostream>
using namespace std;
#include<string.h>
int a[10]={2,3,4,4,2,4,2,8,9};
char c[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};

void func(int i,char result[10])
{
    if(i==10)
    {
       int l=strlen(result);
       for(int j=0;j<l;j++)
           cout<<result[j];
    }

    else
    {
        if(10*a[i]+a[i+1]<26)
        {
            strcat(result,"c[10*a[i]+a[i+1]]");
            func(i+2,result);
        }

        strcat(result,"c[a[i]]");
        func(i+1,result);
    }
}

int main()
{

    func(0,"");
}

我无法找出错误。你能帮我吗?

最佳答案

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int a[9]={2,3,4,4,2,4,2,8,9};
char c[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};

void func(int i,char result[11])
{
    if(i==10)
    {
      printf ("%s\n", result);
    }
    else
    {
        char * temp = (char *)malloc(11);
        sprintf(temp, "%s%c", result, c[a[i] - 1]);
        func(i+1,temp);
        free(temp);

        if(i < 9 && 10*a[i]+a[i+1] < 26)
        {
            char * temp = (char *)malloc(11);
            sprintf(temp, "%s%c", result, c[10*a[i]+a[i+1] - 1]);
            func(i+2, temp);
            free (temp);
        }
    }
}
int main()
{
    func(0,"");
}

输出

bcddbdbhi
bcddxbhi
wddbdbhi
wddxbhi

代码中潜在的致命问题

  1. strcat(result,"c[10*a[i]+a[i+1]]");strcat(result,"c[a[i]]");您将这些字符串连接到 result它的大小仅为 10,而不是连接与该数字对应的字符。

其他问题

  1. 内部if(10*a[i]+a[i+1]<26)您正在更改 result 的内容,当递归结束时,result的值与进入函数时的值不一样。因此,最好在内部创建新字符串,并在任务结束时释放它们。

建议

  1. 尽量不要混合使用 C 和 C++ 函数。

关于c++ - 找到数字数组的所有可能的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18720712/

相关文章:

c++ - C++ 中的隐式转换

c++ - 确保静态 bool 检查的线程安全

java - 递归地在网格中查找单词

recursion - 使用 CPS 删除 Scheme 中的子序列函数(深度递归)

java - 解决 N 个皇后的回溯问题

c++ - 二叉搜索树成员函数

c++ - 具有来自同一个 DLL 的全局变量的多个实例

将数据分片成数据包的算法

algorithm - 了解如何设计 Nest Thermostat 使用的算法的资源?

algorithm - 递归微分基本表达式