由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 贴一道题,帮忙做做code review (How can we generate all possibilities on braces )
相关主题
问一个阿三出的面试题: 什么是iterator invalidation?Amazon onsite面经
google题Graph DFS Iterative
what is the internal implementation of DequeGoogle onsite归来
讨论一道题:找出一个board上的所有单词对自己DFS能力彻底的绝望了。
问个算法题:寻找两个点之间的所有路径IDDFS
问一个coding的skill一棵树,如果找最深的至少有两个子节点的节点?
攒人品,回答问题面试题总结(7) - Tree
A面试题F家面经
相关话题的讨论汇总
话题: deque
进入JobHunting版参与讨论
1 (共1页)
c*****e
发帖数: 74
1
/*
How can we generate all possibilities on braces ?
N value has given to us and we have to generate all possibilities.
**Examples:**
1) if N == 1, then only one possibility () .
2) if N==2, then possibilities are (()), ()()
3) if N==3, then possibilities are ((())), (())(),()()(), ()(()) ...
Note: left and right braces should match. I mean )( is INVALID for the N==1
How can we solve this problem by using recurrence approach ?
*/
#include
using namespace std;
void PrintStack(deque& s)
{
for(deque::iterator iter = s.begin();iter!=s.end();iter++)
{
cout<<*iter;
}
cout< }
void EnumerateBracePairHelp(deque& s, int nCurrLeftBraceNum, int
nMaxPairNum)
{
if(s.size() >= 2*nMaxPairNum)
{
PrintStack(s);
return;
}

// -- check whether we can put a '('
if(nCurrLeftBraceNum < nMaxPairNum)
{
s.push_back('(');
EnumerateBracePairHelp(s, nCurrLeftBraceNum +1, nMaxPairNum);
s.pop_back();
}
// -- check whether we can put a ')'
if( s.size() - nCurrLeftBraceNum < nCurrLeftBraceNum )
{
s.push_back(')');
EnumerateBracePairHelp(s, nCurrLeftBraceNum, nMaxPairNum);
s.pop_back();
}
}
void EnumerateBracePair(int k)
{
if(k<=0)
return;
deque s;
EnumerateBracePairHelp(s,0,k);
}
int main()
{
EnumerateBracePair(5);
return 0;
}
b*****e
发帖数: 474
2
很不错了。细节可以再推敲一下,算法本身(基于DFS的递归)没问题,C++
的掌握也不错。当个 developer 够了哈。
我的版本,给你参考一下吧:
#include
#include // i like arrays
#include // for atoi()
using namespace std;
void print_parens(int n) {
static vector s; // i just use static vars to save parameter
static numLeft = 0; // passing
static numRight = 0;
if (n<0) return;
if (n==0) {
for( int i=0; i // save the extra recursion when there are n '('s already -
// so you don't need to construct a size 2*n string
for( int i=0; i cout << endl;
return;
}
// DFS steps:
s.push_back('('); numLeft++;
print_parens(n-1); // you don't need to check numLeft s.pop_back(); numLeft--;
if (numRight s.push_back(')'); numRight++;
print_parens(n);
s.pop_back(); numRight--;
}
}
int main(int argc, char *argv[]) {
if ( argc == 1 ) { cour << "print_paren n" << endl; }
else {
int n = atoi(argv[1]);
print_parens(n);
}
return 0;
}
1 (共1页)
进入JobHunting版参与讨论
相关主题
F家面经问个算法题:寻找两个点之间的所有路径
是不是所有recursion能解决的问题都有iterative的解法问一个coding的skill
新鲜G面经攒人品,回答问题
贡献Amazon的电面经验A面试题
问一个阿三出的面试题: 什么是iterator invalidation?Amazon onsite面经
google题Graph DFS Iterative
what is the internal implementation of DequeGoogle onsite归来
讨论一道题:找出一个board上的所有单词对自己DFS能力彻底的绝望了。
相关话题的讨论汇总
话题: deque