递归创建——nested()

发布于 2024-10-20 08:40:32 字数 1645 浏览 1 评论 0原文

我正在尝试解决“经典”动态规划问题之一。问题是 - 给定一个数字作为输入,生成可能的嵌套条件。

编辑:正如下面的 temp 所指出的,我将首先尝试使用递归来解决这个问题,然后尝试使用动态编程。

IE。 if n = 3

O/p
((()))
()()()
(())()
()(())
(()())

我解决这个问题的方法基于两个规则。

  1. 如果最大数量 ( 这里3)未达到且数量 左大括号的个数小于或等于 到右大括号的数量。
  2. 仅当最大数量时才添加右大括号 是 未达到及权利数量 大括号的数量小于左大括号的数量 大括号。

从理论上讲,它们听起来是正确的,但它完全落在下面的源上。请原谅硬编码。

编辑:我做了一些修改,并且离解决方案更近了一步:)

 #include <iostream>
#include <vector>
#include <string>

using namespace std;

void printPar(int l,int r,string s)
{
    if(l > 3 || r > 3 || r >l)
        return;



    if(l==3 && r==3)
    {
        cout<<s<<endl;
        return;
    }
    else
    {

         if((l<3))
         {
            s+="<";
            l = l+1;
            printPar(l,r,s);
         }
          if(r<3 && r < l)
         {
             s+=">";
             r = r+1;
            printPar(l,r,s);
         }
       //  cout<<"Exiting "<<l<<" & "<<r<<" "<<s<<endl;
    }
}




int main()
{
    string s;
    printPar(0,0,s);
    return 0;
}

调试:

<<<>>>
<<<>>>
<<><>>
<<><>>
<><<>>
<><<>>
<><><>
<><><>

我明白为什么列表中有重复的值。即,一旦使用递归调用函数并最终执行下一个分支。第二次打印是由于它本身落在第二个分支上的函数。有什么办法可以处理这个问题吗?我实在不想走全球统一的路线。

另外,在我的脑海中,这段代码应该打印 (())() - 但它没有:(

有人可以指出错误吗?

谢谢!

我知道情况需要一些调整,但我一直在无休止地盯着这个。哈普!

I am trying to solve one of the "classic" dynamic programming problems. The problem is - Given a number as input , generate possible nested conditions.

Edit: as pointed out by temp below , i am going to first try and sort this out using recursion and then try with dynamic programming.

ie. if n = 3

O/p
((()))
()()()
(())()
()(())
(()())

My approach to the problem is based on two rules.

  1. Add a "(" brace if max number (
    here 3 ) is not reached and number
    of left braces is less than or equal
    to number of right braces.
  2. Add a right brace only if max number
    is
    not reached and number of right
    braces is less than number of left
    braces.

In theory they sound right ,but it falls face flat on the below source. Please excuse the hard-coding.

Edit : I have made some modifications and moved an inch closer to the solution :)

 #include <iostream>
#include <vector>
#include <string>

using namespace std;

void printPar(int l,int r,string s)
{
    if(l > 3 || r > 3 || r >l)
        return;



    if(l==3 && r==3)
    {
        cout<<s<<endl;
        return;
    }
    else
    {

         if((l<3))
         {
            s+="<";
            l = l+1;
            printPar(l,r,s);
         }
          if(r<3 && r < l)
         {
             s+=">";
             r = r+1;
            printPar(l,r,s);
         }
       //  cout<<"Exiting "<<l<<" & "<<r<<" "<<s<<endl;
    }
}




int main()
{
    string s;
    printPar(0,0,s);
    return 0;
}

Debug:

<<<>>>
<<<>>>
<<><>>
<<><>>
<><<>>
<><<>>
<><><>
<><><>

I understand why there are duplicate values in the list. i.e once the function is called using recursion and ends up following the next branch on execution. The second print is due to the function it self falling on the second branch. Is there any way to handle this ? I really do not want to go the global-set route.

Also , in my head this code should print (())() - Yet it does not :(

Can some one please point out the error ?

Thanks!

I know the condition needs some tweaking , but i have been staring at this endlessly. Halp!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一个人的夜不怕黑 2024-10-27 08:40:32

目前,您的解决方案没有利用动态编程。如果你想在这里使用DP,你需要递归地思考问题。幸运的是,这个问题有一个很好的递归公式:

  1. 只有一种方法可以从没有括号的情况得到平衡的括号,那就是根本没有括号。
  2. 如果需要平衡 n + 1 对括号,则可以按如下方式生成所有平衡括号:对于从 0 到 n 的所有 i,构造 (X)Y 形式的每个字符串,其中 < code>X 是由 i 个平衡括号组成的字符串,Y 是由 n - i 个平衡括号组成的字符串。

这种设置的美妙之处在于,要计算 n + 1 个平衡括号的所有字符串,您只需要知道如何为 0, 1, 2, ..., n + 1 创建平衡括号。因此,您可以解决这个问题通过迭代构建 n = 0、1、2、...等的解决方案,并重用您在之前步骤中生成的结果。

希望这有帮助!

Right now, your solution doesn't take advantage of dynamic programming. If you want to use DP here, you'll need to think about the problem recursively. Fortunately, there's a great recursive formulation to this problem:

  1. There is only one way to make balanced parentheses from no parentheses, which is to have no parentheses at all.
  2. If you have n + 1 pairs of parentheses to balance, then you can generate all balanced parentheses as follows: for all i from 0 to n, construct every string of the form (X)Y, where X is a string of i balanced parentheses and Y is a string of n - i balanced parentheses.

The beauty of this setup is that to compute all strings of n + 1 balanced parentheses, you only need to know how to make balanced parentheses for 0, 1, 2, ..., n + 1. Consequently, you can solve this problem by iterative constructing solutions for n = 0, 1, 2, ..., etc. and reusing the results you produced at earlier steps.

Hope this helps!

浮生未歇 2024-10-27 08:40:32

我认为这应该可以解决你的问题。

// this map will contain all valid balanced paranthesis expressions
// string will hold expressions
// int for holding 'n' ie number of '('
map<string,int> mvc;

//fn to create all possible balanced set of paranthesis, for given n
void printAllBP(int);
//print fn
void printAll(int);

int main()
{
    int n;
    cout << "Enter n: ";
    cin >> n;

    printAllBP(n);
    printAll(n);

    system("pause");
    return 0;
}

void printAllBP(int n)
{
    if (0==n)
    {
        mvc.insert(pair<string,int>("",0));
        return;
    }    

    printAllBP(n-1);

    map<string,int>::iterator it;
    for (it=mvc.begin();it!=mvc.end();++it)
    {
        if((n-1)==(*it).second)
        {
            string t=(*it).first;
            mvc.insert(pair<string,int>("()"+t,n));
            mvc.insert(pair<string,int>("("+t+")",n));
            mvc.insert(pair<string,int>(t+"()",n));
        }
    }
}

void printAll(int n)
{
    cout << "Printing all possiblities for '" << n << "':\n";
    map<string,int>::iterator it;
    for ( it=mvc.begin();it != mvc.end();++it)
    {
        if(n==(*it).second)
            cout << "\n" << (*it).first;
    }
    cout << "\n";
}

I think this should solve your problem.

// this map will contain all valid balanced paranthesis expressions
// string will hold expressions
// int for holding 'n' ie number of '('
map<string,int> mvc;

//fn to create all possible balanced set of paranthesis, for given n
void printAllBP(int);
//print fn
void printAll(int);

int main()
{
    int n;
    cout << "Enter n: ";
    cin >> n;

    printAllBP(n);
    printAll(n);

    system("pause");
    return 0;
}

void printAllBP(int n)
{
    if (0==n)
    {
        mvc.insert(pair<string,int>("",0));
        return;
    }    

    printAllBP(n-1);

    map<string,int>::iterator it;
    for (it=mvc.begin();it!=mvc.end();++it)
    {
        if((n-1)==(*it).second)
        {
            string t=(*it).first;
            mvc.insert(pair<string,int>("()"+t,n));
            mvc.insert(pair<string,int>("("+t+")",n));
            mvc.insert(pair<string,int>(t+"()",n));
        }
    }
}

void printAll(int n)
{
    cout << "Printing all possiblities for '" << n << "':\n";
    map<string,int>::iterator it;
    for ( it=mvc.begin();it != mvc.end();++it)
    {
        if(n==(*it).second)
            cout << "\n" << (*it).first;
    }
    cout << "\n";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文