【算法】剑指 Offer II 085. 生成匹配的括号|22. 括号生成(java / c / c++ / python / go / rust)

发布时间:2022-06-28 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了【算法】剑指 Offer II 085. 生成匹配的括号|22. 括号生成(java / c / c++ / python / go / rust)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

文章目录

  • 剑指 Offer II 085. 生成匹配的括号|22. 括号生成:
  • 样例 1:
  • 样例 2:
  • 提示:
  • 分析
  • 题解
    • java
    • c
    • c++
    • python
    • go
    • rust
  • 原题传送门:https://leetcode-cn.com/problems/IDBivT/
  • 原题传送门:https://leetcode-cn.com/problems/generate-parentheses/


剑指 Offer II 085. 生成匹配的括号|22. 括号生成:

正整数 n 代表生成括号的对数,请设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

样例 1:

输入:
	n = 3
	
输出:
	["((()))","(()())","(())()","()(())","()()()"]

样例 2:

输入:
	n = 1
	
输出:
	["()"]

提示:

  • 1 <= n <= 8

分析

  • 首先想到的是全排列排列方式,然后再从中挑选满足括号规则的序列。每个字符只可能是 ‘(’ 或者 ‘)’ 两种选择,所以全排列的数量是 22n 个。真正有效的括号序列远远少于这个量。
  • 是否可以直接去穷举生成有效的括号序列呢?
  • 首先要判断什么样的序列是有效的括号序列?
  • 很显然,首先左右括号字符的数量应该相等。
  • 右括号一定是匹配前面某个左括号。
  • 所以只包含左右括号字符,并且从左往右看,右括号数始终小于等于左括号数,最终左右括号数相等的序列就是合理合法合规的括号序列了。

题解

java

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<>();

        this.dfs(n, ans, new char[n * 2], 0, 0);

        return ans;
    }

    private void dfs(int n, List<String> ans, char[] cs, int left, int right) {
        if (left == n && right == n) {
            ans.add(new String(cs));
            return;
        }

        if (left < n) {
            cs[left + right] = '(';
            dfs(n, ans, cs, left + 1, right);
        }
        if (right < left) {
            cs[left + right] = ')';
            dfs(n, ans, cs, left, right + 1);
        }
    }
}

c

#define MAX_SIZE 1430

void dfs(int n, int *returnSize, char **ans, char *cs, int left, int right) {
    if (left == n && right == n) {
        ans[(*returnSize)] = calloc((n * 2 + 1), sizeof(char));
        strcpy(ans[(*returnSize)], cs);
        ++(*returnSize);
        return;
    }

    if (left < n) {
        cs[left + right] = '(';
        dfs(n, returnSize, ans, cs, left + 1, right);
    }
    if (right < left) {
        cs[left + right] = ')';
        dfs(n, returnSize, ans, cs, left, right + 1);
    }
}

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
char **generateParenthesis(int n, int *returnSize) {
    *returnSize = 0;
    char **ans = malloc(MAX_SIZE * sizeof(char *));
    char *cs = calloc((n * 2 + 1), sizeof(char));
    dfs(n, returnSize, ans, cs, 0, 0);
    return ans;
}

c++

class Solution {
private:
    void dfs(int n, vector<string> &ans, string &buf, int left, int right) {
        if (left == n && right == n) {
            ans.push_back(buf);
            return;
        }

        if (left < n) {
            buf.push_back('(');
            dfs(n, ans, buf, left + 1, right);
            buf.pop_back();
        }
        if (right < left) {
            buf.push_back(')');
            dfs(n, ans, buf, left, right + 1);
            buf.pop_back();
        }
    }

public:
    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        string buf;
        dfs(n, ans, buf, 0, 0);
        return ans;
    }
};

python

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        ans = []

        def dfs(s, left, right):
            if left == n and right == n:
                ans.append(''.join(s))
                return
            if left < n:
                s.append('(')
                dfs(s, left + 1, right)
                s.pop()
            if right < left:
                s.append(')')
                dfs(s, left, right + 1)
                s.pop()

        dfs([], 0, 0)
        return ans
        

go

func generateParenthesis(n int) []string {
    var ans []string

	var dfs func(cs []byte, left int, right int)
	dfs = func(cs []byte, left int, right int) {
		if left == n && right == n {
			ans = append(ans, string(cs))
			return
		}

		if left < n {
			cs[left+right] = '('
			dfs(cs, left+1, right)
		}
		if right < left {
			cs[left+right] = ')'
			dfs(cs, left, right+1)
		}
	}

	dfs(make([]byte, n*2), 0, 0)

	return ans
}

rust

impl Solution {
    pub fn generate_parenthesis(n: i32) -> Vec<String> {
        let mut ans = Vec::new();

        fn dfs(n: usize, ans: &mut Vec<String>, buf: &mut String, left: usize, right: usize) {
            if left == n && right == n {
                ans.push(buf.clone());
                return;
            }
            if left < n {
                buf.push('(');
                dfs(n, ans, buf, left + 1, right);
                buf.pop();
            }
            if right < left {
                buf.push(')');
                dfs(n, ans, buf, left, right + 1);
                buf.pop();
            }
        }

        dfs(n as usize, &mut ans, &mut String::new(), 0, 0);

        ans
    }
}

【算法】剑指 Offer II 085. 生成匹配的括号|22. 括号生成(java / c / c++ / python / go / rust)


原题传送门:https://leetcode-cn.com/problems/IDBivT/

原题传送门:https://leetcode-cn.com/problems/generate-parentheses/


非常感谢你阅读本文~ 欢迎【👍点赞】【⭐收藏】【📝评论】~ 放弃不难,但坚持一定很酷~ 希望我们大家都能每天进步一点点~ 本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~


脚本宝典总结

以上是脚本宝典为你收集整理的【算法】剑指 Offer II 085. 生成匹配的括号|22. 括号生成(java / c / c++ / python / go / rust)全部内容,希望文章能够帮你解决【算法】剑指 Offer II 085. 生成匹配的括号|22. 括号生成(java / c / c++ / python / go / rust)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: