427 - 生成括号

2017.10.20

f(n)的值就是在f(n-1)的基础上,遇到左括号就加一个(),然后再在开头加一个()

public class Solution {
    /*
     * @param n: n pairs
     * @return: All combinations of well-formed parentheses
     */
 	public List<String> generateParenthesis(int n){
		Set<String> set = generate(n);
		List<String> res = new LinkedList<>();
		for(String s :set){
			res.add(s);
		}
		return res;
	}
	public Set<String> generate(int n){
	        // write your code here
		Set<String> set = new HashSet<String>();
		set.add("");
		if(n == 0){
			return set;
		}
		for(int i = 1; i <= n; i++){
			Set<String> setTmp = new HashSet<String>();
			for(String s : set){
				setTmp.add("()" + s);
				for(int j = 0; j < s.length(); j++){
					if(Character.toString(s.charAt(j)).equals("(")){
						String newString = s.substring(0, j+1) + "()" + s.substring(j+1);
						setTmp.add(newString);
					}
				}
			}
			System.out.println("当n为" + i + "时,setTmp里的内容有:");
			for(String s : setTmp){
				System.out.print(s + ";");
			}
			System.out.println();
			set.clear();
			set.addAll(setTmp);
		}
		return set;
	}
}


C++实现括号生成主要有回溯法和递归插入法两种方法: ### 回溯法 回溯法的思路是每次判断左括号数小于 `n`,右括号数小于左括号数,只有在序列仍然保持有效时才添加 `'('` 或 `')'`。通过跟踪到目前为止放置的左括号和右括号的数目来实现这一点,如果还剩一个位置,可以开始放一个左括号;如果右括号数量不超过左括号的数量,可以放一个右括号 [^2]。 ```cpp #include <iostream> #include <vector> #include <string> using namespace std; class Solution { public: void backtrack(vector<string>& ans, string cur, int open, int close, int max) { if (cur.length() == max * 2) { ans.push_back(cur); return; } if (open < max) { backtrack(ans, cur + "(", open + 1, close, max); } if (close < open) { backtrack(ans, cur + ")", open, close + 1, max); } } vector<string> generateParenthesis(int n) { vector<string> result; backtrack(result, "", 0, 0, n); return result; } }; ``` ### 递归插入法 递归插入法的思路是要生成 `n` 个情况时,往 `n - 1` 的结果里面插入,同时设定一个退出条件。使用哈希表进行去重 [^3]。 ```cpp #include <iostream> #include <vector> #include <string> #include <unordered_map> using namespace std; class Solution { public: vector<string> generateParenthesis(int n) { if (n == 1) return {"()"}; // 递归的退出条件 unordered_map<string, int> a; // 定义哈希表用于去重 vector<string> res; string tmp; for (auto& s: generateParenthesis(n - 1)) { // 遍历n-1 for (int i = 0; i != 2 * (n - 1); ++i) { // 遍历整个数组,n对括号字符串长度就是2n tmp = s.substr(0, i) + "()" + s.substr(i, 2 * (n - 1)); if (a[tmp] == 0) { // 去重,如果这个组合没有出现过(键对应的值为0),就放入res中,并且将对应键的其值设置为1 ++a[tmp]; res.emplace_back(tmp); } } } return res; } }; ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值