Re: [閒聊] 每日leetcode已回收

看板Marginalman作者 (神楽めあ的錢包)時間1年前 (2024/04/02 23:06), 編輯推噓1(101)
留言2則, 2人參與, 1年前最新討論串87/1548 (看更多)
22. Generate Parentheses 有n組括號,寫一個function,可以產生所有括號的組合 思路: 當你放了一個左括號才能再放一個右括號 所以設兩個變數L、R : L是左括號剩下的數量、R是右括號剩下的數量 一開始L=n、R=0 每次放了一個左括號就將L-1、R+1 同理放了一個右括號就將R-1 就這樣一直到L+R==0就是一組組合了 照上面的規則寫一個遞迴函式 golang code : func generateParenthesis(n int) []string { if n == 1 { return []string{"()"} } return backtrack("", n, 0) } func backtrack(rec string, l, r int) []string { if l+r == 0 { return []string{rec} } var ans []string if l > 0 { ans = append(ans, backtrack(rec+"(", l-1, r+1)...) } if r > 0 { ans = append(ans, backtrack(rec+")", l, r-1)...) } return ans } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 42.72.152.240 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1712070377.A.8B4.html

04/02 23:07, 1年前 , 1F
你的每日怎麼跟我不一樣
04/02 23:07, 1F

04/02 23:07, 1年前 , 2F
今天每日寫過了 隨便挑一題來寫
04/02 23:07, 2F
文章代碼(AID): #1c31xfYq (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1c31xfYq (Marginalman)