Appending to two dimensional List<string>

Viewed 59

I'm working on an algorithm that checks if its possible to recreate a word from list of strings (smaller words) and returns all the combinations if the word can be reconstructed, else an empty list.

I found it in one of the lectures about dynamic programming. I got it right till the point where I need to accumulate the result of previously found solutions with the current iteration of loop.

My code returns an List of List of strings where each contains single word that recreates the string. I assume its because my algorithm fails to append the results correctly into the table, instead it overrides it.

Code -

        List<string> wordbank = new List<string>() { "purp", "p", "ur", "le", "purpl" };
        string target = "purple";
        Dictionary<int, List<List<string>>> table = new();

        for (int i = 0; i < target.Length + 1; i++)
        {
            table[i] = new();
        }

        table[0] = new ();


        for (int i = 0; i <= target.Length; i++)
        {  
            foreach (var word in wordbank)
            {
                try
                {
                    if (target.Substring(i, word.Length) == word)
                    {
                        var tbd = table[i];
                        tbd = tbd.Append(new List<string> { word }).ToList();
                        foreach (var item in tbd)
                        {
                            table[i + word.Length] = table[i + word.Length].Append(item).ToList();
                        }  
                    }
                }
                catch
                {

                    
                }
                    
            }
        }
        foreach (var item in table[target.Length])
        {
            Console.WriteLine("__");
            foreach (var v in item)
            {
                Console.WriteLine(v + " ,");
            }
        }

Result - __ purp , __ p , __ ur , __ p , __ le ,

Expected Result - __ purp ,le, __ p, ur, p, le,

0 Answers
Related