深度优先遍历解决括号生成问题

namespace ConsoleApp10
{
    class Program
    {
        static void Main(string[] args)
        {
            Solution solution = new Solution();
            solution.generateParenthesis(3);
        }
    }
    class Solution
    {
        public List<string> generateParenthesis (int n)
        {
            List<string> res = new List<string>();
            if(n == 0)
            {
                return res;
            }
            dfs("", n, n, res);
            return res;
        }
        private void dfs(string curStr , int left ,int right,List <string> res)
        {
            if(left == 0 && right == 0)
            {
                res.Add(curStr);
                return;
            }
            if(left > 0)
            {
                dfs(curStr + "(", left - 1, right, res);
            }
            if(right>0 && left < right)
            {
                dfs(curStr + ")", left, right - 1, res);
            }
        }
    }
}

发布了58 篇原创文章 · 获赞 7 · 访问量 3745

猜你喜欢

转载自blog.csdn.net/xy_learning/article/details/103042631