22. Generate Parentheses
https://leetcode.com/problems/generate-parentheses/
brute force
gen all the permutation of parentheses, then validate them one by one
O(2^2n*n), ๆๅพไนไธ n ๆฏ validate ็
2. dfs+backtracking
from "" to dfs gen string
ไพ็ถๅฏไปฅ็ซๅบๆจน็ๅ, ๆจน็ๅๅพ้่ฆ
use adding
ไฝ้้กๆฏๅฏไปฅๅจไธญ้ๅฐฑๅคๆทๆฏๅฆๅๆณ n=3, ๅชๆไธๅๅทฆๆฌ่ไธๅๅณๆฌ่
้้กๅช่ฆ้ๅฐๅฆๆญคๆขไปถๅฐฑๅฏไปฅๅๆณ(็พไธๅ ็บ้้กๅชๆ()) ๅทฆ้จๆๅฏไปฅๅ ๅฅ่ถ ๆจ๏ผn=3๏ผ ๅณไธ่ฝๅ ๅบ็พ, ๅทฆๅๆธ>ๅณๅๆธ
n > left > right, so n > right ๆไปฅไธ็จๅฏซ
time complexity:
This assumes you are doing constant amount of work in each call. In general, if you are doing k amount of work(outside calling functions recursively), then time complexity will be O(b^d * k)., O(2^d*k)
Taking the above example, n= 3 pairs. 2^0+2^1+2^2+..........+2^6.
Here b is 2, d is 6 as there are 6 levels.
https://leetcode.com/articles/generate-parentheses/
another way, use subtract
Last updated