leetcode的递归题目汇总。递归题目很多,不过有些不分到这个目录下。
Generate Parentheses:
题目描述:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
这种题目递归时妥妥的。
code:
class Solution {
public:
void rec_gen(vector& ans,int left,int right,int n,string str){
if(left==n&&right==n){
ans.push_back(str);
return;
}
if(left generateParenthesis(int n) {
vector ans;
if(n==0) return ans;
string s;
rec_gen(ans,0,0,n,s);
return ans;
}
};
Unique Binary Search Trees II:
题目描述:
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3这个题跟上面的题对比一下,就是我在 面试总结之-递归算法分析里面讲到的两种框架,先递归还是先处理。这个题是先递归,再处理。所以,这个题的递归代码,解是作为结果return回来的而不是作为参数传入。
code:
class Solution {
public:
vector generate(int st,int end){
vector result;
if(st>end) { result.push_back(NULL); return result;}
for(int i=st;i<=end;i++){
vector left = generate(st,i-1); //生成左右子树
vector right = generate(i+1,end);
for(int j=0;jleft = left[j];
head->right = right[k];
result.push_back(head);
}
}
}
return result; //返回结果
}
vector generateTrees(int n) {
return generate(1,n);
}
};
题目描述:
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab"
,
Return
[ ["aa","b"], ["a","a","b"] ]这个题目也是可以先处理再递归的,所以解作为参数传入了。(而且这个题目也很容易可以写成先递归,回来再处理,这样的话解可以作为返回值)
class Solution {
public:
bool isPalindrome(string& s,int st,int e){
for(int i=st,j=e;i>& ans,vector& tmp){
if(st==s.length()){
ans.push_back(tmp);
return;
}
for(int i=st+1;i<=s.length();i++){
if(isPalindrome(s,st,i-1)){
tmp.push_back(s.substr(st,i-st));
rec_part(s,i,ans,tmp);
tmp.pop_back();
}
}
}
vector> partition(string s) {
vector> ans;
int len = s.length();
if(len==0) return ans;
vector tmp;
rec_part(s,0,ans,tmp);
return ans;
}
};
这个代码实际上效率很低,应该有不少地方可以优化= =!不过暂时没有时间,先放上来了,至少是可以过leetcode的大数据的。
====================以后补充的分界线====================以后补充的分界线====================以后补充的分界线==============