You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

相邻字符组合生成程序结果缺失,求递归/DP解决方案

相邻字符合并组合生成问题

需求说明

生成所有仅合并相邻两个字符的组合,示例如下:

  • 输入[a,b,c],输出:[a,b,c], [ab,c], [a,bc]
  • 输入[a,b,c,d],输出:[a,b,c,d], [ab,c,d], [a,bc,d], [a,b,cd], [ab,cd]
  • 输入[a,b,c,d,e],正确输出应包含:[a,b,c,d,e], [ab,c,d,e], [a,bc,d,e], [a,b,cd,e], [a,b,c,de], [ab,cd,e], [a,bc,de], [ab,c,de]

问题现状

本人编写的C#程序缺失了输入[a,b,c,d,e]时的最后一个结果[ab,c,de],当前输出情况见附图。想请教是否需要用递归/动态规划来解决这个问题,寻求相关帮助。

现有代码

public class Program
{
    public static void Main(string[] args)
    {
        List<string> cases = new List<string> {"a b c", "a b c d", "a b c d e"};
        for (int c = 0; c < cases.Count; c++)
        {
            var result = F(cases[c]);
            Console.WriteLine(cases[c]);
            result.ForEach(Console.WriteLine);
            Console.WriteLine("---------------------------");
        }
    }

    public static List<string> F(string searchTerm)
    {
        List<string> result = new List<string>();
        var terms = searchTerm.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
        if (terms.Count == 1)
            return new List<string> { searchTerm };

        for (int x = 1; x <= 2; x++)
        {
            for (int i = 0; i < terms.Count - 1; i++)
            {
                if (x == 1)
                {
                    int j = i;
                    var joinedWord = terms[j] + terms[j + 1];
                    result.Add(searchTerm.Replace($"{terms[j]} {terms[j + 1]}", joinedWord));
                }

                if (x == 2)
                {
                    int j = i;
                    if (j + 3 < terms.Count)
                    {
                        var firstJoinedWord = terms[j] + terms[j + 1];
                        var secondJoinedWord = terms[j + 2] + terms[j + 3];
                        result.Add(searchTerm.Replace($"{terms[j]} {terms[j + 1]} {terms[j + 2]} {terms[j + 3]}", firstJoinedWord + " " + secondJoinedWord));
                    }
                }
            }
        }
        

        return result;
    }
}

内容的提问来源于stack exchange,提问作者Varun Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 00:53:30