TGViewer
PHP | LeetCode PHP | LeetCode @easy_php_task · 1.34K subscribers
Post #1541 77
Задача №22. Generate Parentheses
Сложность: medium

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

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


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

1⃣Использовать рекурсию для генерации всех возможных комбинаций.

2⃣Если еще можно открыть скобку — добавляем ( и уменьшаем счетчик открытых.

3⃣Если есть закрытые скобки, которые можно закрыть — добавляем ).

😎 Решение:
class Solution { 

private array $answer = [];
private string $current = '';

function generateParenthesis($n) {
$this->generateParentheses($n, 0);
return $this->answer;
}

function generateParentheses($toOpen, $toClose) {
if ($toOpen == 0 && $toClose == 0) {
$this->answer[] = $this->current;
return;
}

if ($toOpen > 0) {
$this->current .= '(';
$this->generateParentheses($toOpen - 1, $toClose + 1);
$this->current = substr($this->current, 0, -1);
}

if ($toClose > 0) {
$this->current .= ')';
$this->generateParentheses($toOpen, $toClose - 1);
$this->current = substr($this->current, 0, -1);
}
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_php_task
  1. Oct 9, 2026Задача: 71. Simplify Path Сложность: medium Дан абсолютный путь для файловой системы в сти…
  2. Oct 7, 2026🔥 Скрытые вакансии с удаленной работой для PHP разработчика, которые нигде больше не публ…
  3. Oct 6, 2026Задача: 166. Fraction to Recurring Decimal Сложность: medium Даны два целых числа, предста…
  4. Oct 5, 2026Задача: 1024. Video Stitching Сложность: medium Вам дана серия видеоклипов со спортивного…
  5. Oct 5, 2026Задача: 924. Minimize Malware Spread Сложность: hard Вам дана сеть из n узлов, представлен…
  6. Oct 4, 2026Задача: 821. Shortest Distance to a Character Сложность: easy Дана строка s и символ c, ко…
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 →