LeetCode刷題Medium篇Generate Parentheses
阿新 • • 發佈:2018-12-24
題目
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
十分鐘嘗試
感覺跟排列組合類似,可以用相類似的方法,但是不知道如何下手,來,看看人家的思路,繼續學習一下回溯法
class Solution { public List<String> generateParenthesis(int n) { List<String> list=new ArrayList(); backTrace(list,"",0,0,n); return list; } private void backTrace(List<String> list,String str,int openCount,int closeCount,int n){ if(str.length()==2*n){ //類似於排列組合的tmplist的size等於nums長度,表示一種可能組合完畢 list.add(str); } if(openCount<n){ backTrace(list,str+"(",openCount+1,closeCount,n); } if(closeCount<openCount){ backTrace(list,str+")",openCount,closeCount+1,n); } } }