Conversation
| std::vector<std::string>& all_parentheses | ||
| ) { | ||
| if (current_parenthesis.size() == 2 * n) { | ||
| all_parentheses.emplace_back(current_parenthesis); |
There was a problem hiding this comment.
この場合だと、push_backと同じではないですか?どういった意図で使い分けているのか気になりました。
| } | ||
| current_parentheses = std::move(next_parentheses); | ||
| } | ||
| return std::vector<std::string>(current_parentheses.begin(), current_parentheses.end()); |
There was a problem hiding this comment.
return { current_parentheses.begin(), current_parentheses.end() };とも書けるものの、ぱっと見で意味が分からない可能性があるため、避けたほうが良いかもしれません。
| std::string& current_parenthesis, | ||
| std::vector<std::string>& all_parentheses | ||
| ) { | ||
| if (current_parenthesis.size() == 2 * n) { |
There was a problem hiding this comment.
backtrack 解法の終了条件はペア数で管理する(
n_close_used == n)のが良いかも?まあ好みの範囲かもしれない。
に関連して、結構悩ましいなと思いました。
まず、頭から読んだときの感想として、「n_open_used != n_close_used な場合でもこの条件が満たされるな。大丈夫なのかな」と思いました。で、次とその次のブロックを読んで、どうやら同じになるようにカッコが追加されていくらしいぞ、ということで安心しました。
自分が書いたときには (n_open_used == n_close_used) && (n == n_open_used) としたのですが、こっちもこっちで「n_open_used や n_close_used が current_parenthesis の状態に合わせて正しく更新されているんだろうな?」という心配はあります。が、それでもこっちの心配の方が少ないかなと感じました(個人的には)。
他の選択肢としては、カッコの対応を検証するサブルーチン IsValid を用意して、(current_parenthesis.size() == 2 * n) && IsValid(current_parenthesis) みたいにする、というのも思いつきました。これはこれで、そんなに後続のロジックを信用してないんかい、という気持ちもあります。
問題
https://leetcode.com/problems/generate-parentheses/description/
次の問題
283. Move Zeroes