Leetcode_22

来源:互联网 发布:电子软件合同范本 编辑:程序博客网 时间:2024/05/16 12:52

using System;using System.Collections.Generic;namespace Leetcode_22{public class Solution{public IList<string> GenerateParenthesis(int n){IList<string> list = new List<string>();backtrack(list, n, "");return list;}private void backtrack(IList<string> list, int n, string result){if (is_a_solution(result, n)){process_solution(list, result);}else {if (result.Length == 2 * n)return;char[] c = new char[2] { '(', ')' };for (int i = 0; i < 2; i++){result += c[i];backtrack(list, n, result);result = unmake_move(result);}}}private string unmake_move(string result){string str = "";for (int i = 0; i < result.Length-1; i++){str += result[i];}return str;}private bool is_a_solution(string str, int n){if (str.Length == 2*n){return query(str);}else {return false;}}private bool query(string str){Stack<char> s1 = new Stack<char>();int count = 0;while (count < str.Length){if (count == 0 && str[count] == ')'){return false;}else {if (str[count] == ')'){if (s1.Count == 0)return false;else {char c = s1.Peek();if (c != '('){return false;}else {s1.Pop();}}}else {s1.Push(str[count]);}count++;}}if (s1.Count == 0)return true;elsereturn false;}private void process_solution(IList<string> list, string result){list.Add(result);}}}


0 0
原创粉丝点击