class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
searchDfs(n, n, "", result);
return result;
}
void searchDfs(int left, int right, string pair, vector<string>& result){
if(left > right)
return;
if(left == 0 && right == 0){
result.push_back(pair);
}
else{
if(left>0)
searchDfs(left-1, right, pair+'(', result);
if(right>0)
searchDfs(left, right-1,pair+')', result);
}
}
};
需要列出所有组合的情况下,一般考虑深度优先搜索(DFS),同时深度优先搜索一般和递归一起使用,需要特别注意,多理解。