Varun Aggarwal

Varun Aggarwal

  • 1.7k
  • 31
  • 528

hi can someone tell me why bool function is returning false

Mar 28 2022 8:16 PM

hi 

I am writing a function canConstruct() that will take targeSum and a List of strings containing substrings. The function should return a boolean indicating wheather or not the targetSum can be constructed by concatenating elements of the list.

you may reuse the elements of the list as many times as needed.

my solution:


List<string> abb = new List<string>();
//abb.Add("ab");
abb.Add("abc");
//abb.Add("de");
abb.Add("def");
abb.Add("cdef");
string target = "abcdef";
Console.WriteLine(canConstruct(target,abb));


bool canConstruct(string targetSum, List<string> arrayofstring )
{
   
    if (string.IsNullOrEmpty(targetSum))
    {

        return true;
        
        
    }
    foreach (var rr in arrayofstring)
    {
        if (targetSum.IndexOf(rr) == 0 && rr.Length<=targetSum.Length)
        {
            string new_rr = targetSum.Remove(0, rr.Length);
            canConstruct(new_rr, arrayofstring);
        }

    }

    return false;
}

 

but the problem here is my solution is returning false, despite returning true in one of the callstacks the overall answer is false, also the program is not exiting after true is returned from callstack , can someone pls help.


Answers (1)