代码之家  ›  专栏  ›  技术社区  ›  mettleap

生成所有有效括号

  •  0
  • mettleap  · 技术社区  · 6 年前

    ["((()))","(()())","(())()","()(())","()()()"]
    

    我针对这个问题的代码如下:

    private void allParenthesis(List<String> result, int n){
        if(n == 1){
            result.add("()");
            return;
        }
        allParenthesis(result, n-1);
    
        List<String> newResult = new ArrayList<String>();
        for(String str : result){
            newResult.add("("+str+")");
            newResult.add("()"+str);
            newResult.add(str+"()");
        }
        System.out.println(newResult+" for n:"+n);
        result = new ArrayList<String>(newResult);
    
    }
    

    我在下面的函数中使用这个函数,

    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<String>();
    
        allParenthesis(result,n);
        return result;
    }
    

    ["()"]
    

    3 回复  |  直到 6 年前
        1
  •  3
  •   Mohammad C    6 年前

    您正在丢失已创建的结果,并且没有通过递归传递它。我修正了它并简化为一个函数。使用数组列表也意味着存在重复项。例如。

    Str = "()";
    newResult.add("()"+str); //this will result in ()()
    newResult.add(str+"()"); //this will also result in the same
    

    如果你想要上面的结果,那么继续使用arraylist。如果没有,我建议使用LinkedHashSet作为集合,不要有重复项和链接一次,这样插入的顺序就可以保持。如果不关心结果的顺序,可以使用HashSet。

    -没有重复

    private LinkedHashSet<String> generateParenthesis(int n){
        if(n == 1){
            LinkedHashSet<String> result = new LinkedHashSet<String>();
            result.add("()");
            return result;
        }
        LinkedHashSet<String> result = generateParenthesis(n-1);
    
        LinkedHashSet<String> newResult = new LinkedHashSet<String>();
        for(String str : result){
            newResult.add("("+str+")");
            newResult.add("()"+str);
            newResult.add(str+"()");
        }
        result.addAll(newResult);
        return result;
    }
    

    -保持重复

    private ArrayList<String> generateParenthesis(int n){
        if(n == 1){
            ArrayList<String> result = new ArrayList<String>();
            result.add("()");
            return result;
        }
        ArrayList<String> result = generateParenthesis(n-1);
    
        ArrayList<String> newResult = new ArrayList<String>();
        for(String str : result){
            newResult.add("("+str+")");
            newResult.add("()"+str);
            newResult.add(str+"()");
        }
        result.addAll(newResult);
        return result;
    }
    

    你可以这样使用这个函数。

    LinkedHashSet<String> result = generateParenthesis(3);
    System.out.println(result);
    
        2
  •  1
  •   Kartik    6 年前

    你在抛弃你的孩子 newResult

    改变

    result = new ArrayList<String>(newResult);
    

    result.clear();
    result.addAll(newResult);
    
        3
  •  1
  •   Juan    6 年前

    当你这么做的时候

    result = new ArrayList<String>(newResult);
    

    您正在更新在中定义的变量 allParenthesis 你传过来的那个 generateParenthesis 保持不变。

    改为这样做

    result.clear();
    result.addAll(newResult);