Created
August 11, 2014 04:23
-
-
Save WOLOHAHA/8031ea3f82aa544edc72 to your computer and use it in GitHub Desktop.
Implement an algorithm to print all valid combinations of n-pairs of parentheses.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package POJ; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.List; | |
public class Main { | |
/** | |
* | |
* 9.6 Implement an algorithm to print all valid combinations of n-pairs of parentheses. | |
* | |
* | |
*/ | |
public List<String> getParentheses(int n) { | |
List<String> result = new ArrayList<String>(); | |
if (n <= 0) | |
return result; | |
getResult(result, n, 0, 0, ""); | |
return result; | |
} | |
private void getResult(List<String> result, int n, int positive, | |
int negative, String temp) { | |
// TODO Auto-generated method stub | |
if (negative > positive) | |
return; | |
if (negative + positive == 2 * n) { | |
if (positive == negative) | |
result.add(temp); | |
return; | |
} | |
getResult(result, n, positive + 1, negative, temp + "("); | |
getResult(result, n, positive, negative + 1, temp + ")"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment