Short C# Recursive with Hashset Accepted Solution


  • 1
    L
    public class Solution {
        public IList<string> GenerateParenthesis(int n) {
            List<string> tmp = new List<string>();
            HashSet<string> hs = Generator(n);
    
            tmp = hs.ToList<string>();
            return tmp;
        }
        
        private static HashSet<string> Generator(int n)
        {
            HashSet<string> tmp = new HashSet<string>();
            if (n == 0) return tmp;
            if (n == 1)
            {
                tmp.Add("()");
                return tmp;
            }
            HashSet<string> last = Generator(n - 1);
            foreach(string str in last)
            {
                tmp.Add("()" + str);
                for (int j = 0; j < str.Length / 2; j++)
                    tmp.Add(str.Substring(0, j + 1) + "()" + str.Substring(j + 1));
            }
    
            return tmp;
        }
        
    }

Log in to reply
 

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