Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"
这道题我是用递归的方式做的,用堆栈来判断是否复合条件,同时加上一个判断有多少左括号的函数。
public class Solution {
   	public boolean isValid(String s) {
		boolean result = false;
		if (s == null || s.length() < 2) {
			return false;
		}		
		Stack<Character> st = new Stack<Character>();
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == '('||s.charAt(i) == ')') {
				if (st.isEmpty()) {
					st.push(s.charAt(i));
				} else {
					
					if ((char) st.peek() + s.charAt(i) == 81
							) {
						st.pop();
					} else {
						st.push(s.charAt(i));
					}
				}

			}
		}
		if (st.isEmpty()) {
			result = true;
		} else {
			result = false;
		}

		return result;
	}

	 public List<String> generateParenthesis(int n) {
	        List<String> result = generateParentheMax(n*2,n);
	        return result;
	    }
	
	public List<String> generateParentheMax(int n,int num) {
		if (n < 1) {
			return new ArrayList<String>();
		}
		List<String> ls = null;
		List<String> result = new ArrayList<String>();
		if (n > 1) {
			ls = generateParentheMax(n-1,num);
			
			for (String st : ls) {
				if (isValid(st)) {
					String s1 = st + "(";
					result.add(s1);
				} else {
					String s = st + ")";
					result.add(s);
					if(findCharSumInString(st, '(')<num){
						String s1 = st + "(";
						result.add(s1);
					}
				}
			}

		} else {
			
			String s2 ="(";
			result.add(s2);
			
		}
		return result;
	}

	private int findCharSumInString(String s, char c) {
		int sum = 0;
		if (null == s || s.length() == 0) {
			return sum;
		}
		for (int i = 0; i < s.length(); i++) {
			if (c == s.charAt(i)) {
				sum++;
			}
		}
		return sum;
	}
}


网上有人有个更优美而且更好理解的方法。
public class Solution {
  public List<String> generateParenthesis(int n) {
		ArrayList<String> result = new ArrayList<String>();
		ArrayList<Integer> diff = new ArrayList<Integer>();
	 
		result.add("");
		diff.add(0);
	 
		for (int i = 0; i < 2 * n; i++) {
			ArrayList<String> temp1 = new ArrayList<String>();
			ArrayList<Integer> temp2 = new ArrayList<Integer>();
	 
			for (int j = 0; j < result.size(); j++) {
				String s = result.get(j);
				int k = diff.get(j);
	 
				if (i < 2 * n - 1) {
					temp1.add(s + "(");
					temp2.add(k + 1);
				}
	 
				if (k > 0 && i < 2 * n - 1 || k == 1 && i == 2 * n - 1) {
					temp1.add(s + ")");
					temp2.add(k - 1);
				}
			}
	 
			result = new ArrayList<String>(temp1);
			diff = new ArrayList<Integer>(temp2);
		}
	 
		return result;
	}
}

你可能感兴趣的:(java)