TGViewer
Java | LeetCode Java | LeetCode @easy_java_task · 6.43K subscribers
Post #1640 837
Задача: №22. Generate Parentheses
Сложность: medium

Учитывая n пар круглых скобок, напишите функцию, которая генерирует все возможные комбинации правильных (валидных) круглых скобок.

Пример:
Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"]


👨‍💻 Алгоритм:

1⃣Если n == 1, возвращаем базовый набор: ["()"].

2⃣Для n > 1 вызываем рекурсивную функцию, которая для n - 1 генерирует все предыдущие комбинации и вставляет "()" в каждую возможную позицию каждой строки.

3⃣Используем Set, чтобы избежать дубликатов, так как одна и та же комбинация может получиться при вставке "()" в разные позиции.

😎 Решение:
public List<String> generateParenthesis(int n) {
Set<String> ans = new HashSet<>();
ans = createParenthesis(n, ans);
return new ArrayList<>(ans);
}

private static Set<String> createParenthesis(int n, Set<String> currentList) {
Set<String> temp = new HashSet<>();
if (n <= 0) return new HashSet<>();
if (n == 1) {
temp.add("()");
return temp;
}
currentList = createParenthesis(n - 1, currentList);
for (String parenthesis : currentList) {
for (int i = 0; i <= parenthesis.length(); i++) {
String newStr = parenthesis.substring(0, i) + "()" + parenthesis.substring(i);
temp.add(newStr);
}
}
return temp;
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_java_task
  1. Oct 15, 2026Задача: 229. Majority Element II Сложность: medium Дан массив целых чисел размера n, найди…
  2. Oct 14, 2026Post #2298
  3. Oct 14, 2026Задача: 1332. Remove Palindromic Subsequences Сложность: easy Вам дана строка s, состоящая…
  4. Oct 13, 2026Post #2296
  5. Oct 13, 2026Задача: 1120. Maximum Average Subtree Сложность: medium Дан корень бинарного дерева. Верни…
  6. Oct 12, 2026Задача: 1413. Minimum Value to Get Positive Step by Step Sum Сложность: easy Дан массив це…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →