Java 返回更新的ArrayList<;字符>;删除索引处的指定元素后

Java 返回更新的ArrayList<;字符>;删除索引处的指定元素后,java,arraylist,character,Java,Arraylist,Character,我试图找出在单行中删除索引处的指定元素后是否有可能返回更新的ArrayList,以便将其传递给递归函数。 下面是我的代码片段,它试图在给定n对“()”括号的情况下生成所有有效的括号组合 我关心的是递归函数调用“findallcombinions”,其中经过一些验证后,我希望在每次递归调用时从arrayList库集中删除一个字符。但是sourceSet.remove(index)返回一个字符。相反,我希望在删除一行中的字符后传递更新的列表。可能吗 注意:下面的行在语法上是错误的,只是为了更好地说明

我试图找出在单行中删除索引处的指定元素后是否有可能返回更新的ArrayList,以便将其传递给递归函数。 下面是我的代码片段,它试图在给定n对“()”括号的情况下生成所有有效的括号组合

我关心的是递归函数调用“findallcombinions”,其中经过一些验证后,我希望在每次递归调用时从arrayList库集中删除一个字符。但是
sourceSet.remove(index)
返回一个字符。相反,我希望在删除一行中的字符后传递更新的列表。可能吗

注意:下面的行在语法上是错误的,只是为了更好地说明

 findAllCombinations(sourceSet.remove(index), soFar + singleBracket, singleBracket); .
我确实看了一遍,但没有找到任何帮助

非常感谢您的帮助,谢谢您抽出时间

public class GenerateParenthesis {

    char singleBracket;

    List<String> answerSet = new ArrayList<String>();

    char[] repoSet = {'(',')'};

    public List<String> generateParenthesis(int n) {

        String soFar = "(";

        List<Character> sourceSet = new ArrayList<Character>();

        for(int i = 0;i<n;i++){
            sourceSet.add('(');
            sourceSet.add(')');
        }

        findAllCombinations(sourceSet,soFar,'(');

        return answerSet;

    }


    public void findAllCombinations(List<Character> sourceSet,String soFar,Character toRemove){

        if(sourceSet.isEmpty()){
            answerSet.add(soFar);           // append to a answer set list containing all combinations
            return;
        }

        for(int i = 0;i<2;i++){

           singleBracket = repoSet[i];
           int index = sourceSet.indexOf(singleBracket);
           if(index!=-1) {
               findAllCombinations(sourceSet.remove(index), soFar + singleBracket, singleBracket);
           }
        }
    }


    public static void main(String args[]){

        GenerateParenthesis gp = new GenerateParenthesis();

        List<String> ans = new ArrayList<String>();

        ans = gp.generateParenthesis(3);

    }
}
public类GenerateParenthesis{
字符单括号;
List answerSet=new ArrayList();
char[]repoSet={'(',')};
公共列表生成器属性(int n){
字符串soFar=“(”;
List sourceSet=new ArrayList();
对于(int i=0;i
ArrayList
(可能是大多数
List
实现)来说,是一个可变的数据结构:调用
remove
可以修改列表,而不是返回一个没有删除元素的新列表

如果您想要后一种行为,快速简单的方法是复制列表

// (inside the if...)
// pass the original list to the constructor to make a copy
List<Character> sourceSetCopy = new ArrayList<>(sourceSet);
// modify the copy
sourceSetCopy.remove(index);
// use the modified copy
findAllCombinations(sourceSetCopy, soFar + singleBracket, singleBracket);
//(在if内…)
//将原始列表传递给构造函数以制作副本
List sourceSetCopy=new ArrayList(sourceSet);
//修改副本
sourceSetCopy.remove(索引);
//使用修改后的副本
FindAllCompositions(sourceSetCopy、soFar+单括号、单括号);

可以用两行代码来完成,比如
…{sourceSet.remove(inex);findallcompositions(sourceSet,soFar+singleBracket,…
感谢@Fildor的洞察,但是当每次递归调用产生代码时,我希望源集保留源集的原始值(在递归调用中发生的)在这种情况下不会发生。如果我错了,请纠正我,任何建议都将受到欢迎。在这种情况下,无论如何都需要以不同的方式执行。sourceSet.remove(index)将始终更改列表。您需要传递一个在索引处缺少元素的副本。