C# solution


  • 0
    F

    Step

    • Use recursive to find the result of n-1
    • Add leading "(" to each item of result of n-1
    • Find every "(" add ")" behind it, check if this item exists in list
    public class Solution {
        public IList<string> GenerateParenthesis(int n) {
            return Generates(n);
        }
        
        public List<string> Generates(int n)
        {
            if(n == 0) return new List<string>();
            if(n == 1) return new List<string>(){"()"};
            else
            {
                var result = new List<string>();
                var previousResult = Generates(n-1);
               for(var i=0; i<previousResult.Count; i++)
               {
                   var item = "(" + previousResult[i];
                   var index = -1;
                   while(true)
                   {
                        index = item.IndexOf("(", index + 1);
                        if(index == -1) break;
                       
                        var newItem =  item.Insert(index + 1, ")");
                        if(!result.Contains(newItem)) result.Add(newItem);                  
                   }
               }
            
                return result;
            } 
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.