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 List<String> generateParenthesis(int n) {
    	List<String> list = new ArrayList<String>();
    	solve(n,0,0,"",list);
    	return list;
    }

	private void solve(int n, int left, int right, String string, List<String> list) {
		if (left==n && right==n) {
			list.add(string);
		}
		if (left < n) {
			solve(n,left+1,right,string+'(',list);
		}
		if (right<n && left>right) {
			solve(n,left,right+1,string+')',list);
		}
	}
}

 

你可能感兴趣的:(r)