题目一:
输入括号对数,输出所有的合法组合,比如输入1,输出"()",输入3,输出"()()(), (()()), ()(()), (())(), ((()))"。
思路:比如输入1,输出"()",那么输入2的话,我们就可以在输入1的基础上往左插入一对括号,往右插入一对括号以及把它用括号包含起来。这样的话左边和右边是相同的,我们可以用set集合来去除重复。画个示意图如下:
代码:
import java.util.HashSet;
import java.util.Set;
public class 合法括号 {
public static void main(String[] args) {
Set<String> parenthesis = parenthesis(3);
System.out.println(parenthesis);
System.out.println("==============================");
parenthesis = parenthesis1(3);
System.out.println(parenthesis);
}
/* 逐步生成之递归解法 */
public static Set<String> parenthesis(int n) {
Set<String> s_n = new HashSet<>();
if (n == 1) {
s_n.add("()");
return s_n;
}
Set<String> s_n_1 = parenthesis(n - 1);
for (String eOfN_1 : s_n_1) {
s_n.add("()" + eOfN_1);
s_n.add(eOfN_1 + "()");
s_n.add("(" + eOfN_1 + ")");
}
return s_n;
}
/* 迭代形式 */
public static Set<String> parenthesis1(int n) {
Set<String> res = new HashSet<>(); // 保存上次迭代的状态
res.add("()");
if (n == 1) {
return res;
}
for (int i = 2; i <= n; i++) {
Set<String> res_new = new HashSet<>();
for (String e : res) {
res_new.add(e + "()");
res_new.add("()" + e);
res_new.add("(" + e + ")");
}
res = res_new;
}
return res;
}
}
结果:
注意:这儿的递归思路有误,会漏算。当n=4时,"(())(())"这种情况就打印不出来,不过上面的代码也算是给我们提供了一种递归的思路。下面写出正确的递归思路:
解题思路:括号对的合法序列,已经插入的左括号的数目大于等于右括号的数目。
(1)插入左括号:剩余的括号中,还有左括号;
(2)插入右括号:剩余的括号中,右括号的数目大于左括号的数目;
代码及其结果:
public class 合法括号_1 {
public static void printPar(int l, int r, char[] str, int count) {
if (l < 0 || r < l)
return;
if (l == 0 && r == 0) {
System.out.println(str);
} else {
if (l > 0) {
str[count] = '(';
printPar(l - 1, r, str, count + 1);
}
if (r > l) {
str[count] = ')';
printPar(l, r - 1, str, count + 1);
}
}
}
public static void main(String[] args) {
int count = 4;
char str[] = new char[count * 2];
printPar(count, count, str, 0);
}
}
//结果
/*
(((())))
((()()))
((())())
((()))()
(()(()))
(()()())
(()())()
(())(())
(())()()
()((()))
()(()())
()(())()
()()(())
()()()()
*/
题目二:
判断一个括号字符串是否合法。
思路:直接看代码即可,很容易懂,这里要注意一下中文括号和英文括号是不同的。
代码:
public class Test {
public static void main(String[] args) {
System.out.println(chkParenthsis("()a()", 5));
System.out.println(chkParenthsis("()()", 4));
System.out.println(chkParenthsis(")())", 4));
System.out.println(chkParenthsis("(())", 4));
System.out.println("测试中文括号:"+chkParenthsis("()()", 4));
}
/**
* 检查括号字符串是否合法
* @param A 源串
* @param n 源串长度
* @return
*/
public static boolean chkParenthsis(String A,int n){
if(n%2!=0){
return false;
}
int count = 0;
for (int i = 0; i < A.length(); i++) {
if (A.charAt(i) == '('||A.charAt(i) == '(') { // 避免中文括号
count++;
} else if (A.charAt(i) == ')'||A.charAt(i) == ')') {
count--;
} else
return false;
if (count < 0)
return false;
}
return true;
}
}
结果: