Skip to content

Instantly share code, notes, and snippets.

@WOLOHAHA
Created August 11, 2014 04:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WOLOHAHA/8031ea3f82aa544edc72 to your computer and use it in GitHub Desktop.
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.
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