括号生成,力扣上原题,有一些疑惑

毕业设计工坊 课程设计 1

问:来一个认真负责的大佬,详细列举举例一下回溯的过程,我一直不停的推导void backtrack,例如n=3,我只得到了((()))一个结果,希望详细一点 力扣上的原题的官方解析,回溯法,来一个认真负责的大佬

class Solution {
void backtrack(vector& ans, string& cur, int open, int close, int n) {
if (cur.size() == n * 2) {
ans.push_back(cur);
return;
}
if (open < n) {
cur.push_back('(');
backtrack(ans, cur, open + 1, close, n);
cur.pop_back();
}
if (close < open) {
cur.push_back(')');
backtrack(ans, cur, open, close + 1, n);
cur.pop_back();
}
}
public:
vector generateParenthesis(int n) {
vector result;
string current;
backtrack(result, current, 0, 0, n);
return result;
}
};

回复

共2条回复 我来回复
  • 毕设客栈
    这个人很懒,什么都没有留下~
    评论
    #include <vector>
    #include <string>
    #include <iostream>
    using namespace std;
    class Solution
    {
        void backtrack(vector<string> &ans, string &cur, int open, int close, int n)
        {
            if (cur.size() == n * 2)
            {
                ans.push_back(cur);
                return;
            }
            if (open < n)
            {
                cur.push_back('(');
                cout << cur << endl;
                backtrack(ans, cur, open + 1, close, n);
                cur.pop_back();
                cout << cur << endl;
            }
            if (close < open)
            {
                cur.push_back(')');
                cout << cur << endl;
                backtrack(ans, cur, open, close + 1, n);
                cur.pop_back();
                cout << cur << endl;
            }
        }
    public:
        vector<string> generateParenthesis(int n)
        {
            vector<string> result;
            string current;
            backtrack(result, current, 0, 0, n);
            return result;
        }
    };
    int main(void)
    {
        Solution su;
        vector<string> r = su.generateParenthesis(2);
        cout << "result is: " << endl;
        for (int i = 0; i < r.size(); ++i)
        {
            cout << r[i] << endl;
        }
        return 0;
    }
    
    0条评论
  • 源码客栈
    这个人很懒,什么都没有留下~
    评论
    public class Solution {
        List<string> list=new List<string>();
        public IList<string> GenerateParenthesis(int n) {
            AAA("",n,0);
            return list;
        }
        public void AAA(string str, int left,int right)
        {
            if(left==0&&right==0)
                list.Add(str);
            if(left>0)
            {
                string Lstr= str+"(";
                AAA(Lstr,left-1,right+1);
            }
            if(right>0)
            {
                string Rstr= str+")";
                AAA(Rstr,left,right-1);
            }
        }
    }
    
    0条评论

发表回复

登录后才能评论