首页 > 解决方案 > 为什么 +1 在这里有效,但 ++ 运算符不在这里

问题描述

我正在准备面试并尝试练习递归,这是我对一个要求生成“n”括号的问题的解决方案,即如果 n=1 then[[()]] if n=2 then [[()()] , [(())]] 等等..

这是我的解决方案,但如果我在调用递归函数之前增加 open 它不起作用,我在下面的代码中列出了两者,不知道为什么会这样:

 public List<String> generateParenthesis(int n) {
        List<String> rightAns = new ArrayList<>();
        List<String> wrongAns = new ArrayList<>();
        
        helper(0, 0, "", rightAns, n);     //["((()))","(()())","(())()","()(())","()()()"] for n = 3
        helperWrong(0, 0, "", wrongAns, n);//["((()))"] for n = 3
        
        return rightAns;
    }
    
    public void helper(int open, int close, String cur, List<String> ans, int n){
        if(cur.length() == 2*n){
            ans.add(cur);
            return;
        }
        
        if(open < n){
            //open++; doesn't work
            helper(open+1, close, cur+"(", ans, n);
            
        }
        
        if(close < open){
            //close++; doesn't work
            helper(open, close+1, cur+")", ans, n);
        }
        System.out.println("cur"+cur.toString());
        return;
            
    }
    
    public void helperWrong(int open, int close, String cur, List<String> ans, int n){
        if(cur.length() == 2*n){
            ans.add(cur);
            return;
        }
        
        if(open < n){
            open++; 
            helperWrong(open, close, cur+"(", ans, n);
            
        }
        
        if(close < open){
            close++; 
            helperWrong(open, close, cur+")", ans, n);
        }
        System.out.println("cur"+cur.toString());
        return;
            
    }

标签: javarecursion

解决方案


后缀++运算符在表达式之后进行评估。例如:

a=2;
b=a++; //b=2, a=3

调用函数时相同:

a=2;
foo(a++);
//a=3

void foo(int v){
  //v=2
}

因此,您的递归函数将在递增之前接收该值。


推荐阅读