当前位置: 首页 > 知识库问答 >
问题:

在索引处删除指定元素后返回更新的ArrayList

乐正峰
2023-03-14

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

我关心的是递归函数调用“findAllCombinations”,其中经过一些验证后,我希望在每次递归调用时从arrayList库集中删除一个字符。然而,源集。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);

    }
}

共有1个答案

岑毅庵
2023-03-14

ArrayList(可能是大多数List实现)是一种可变数据结构:调用删除您修改列表而不是返回没有删除元素的新列表。

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

// (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);
 类似资料:
  • 问题内容: 我正在尝试一个练习,在该练习中,我将1000个元素添加到arraylist中,然后再次从列表中系统地删除它们(通过指定索引)。其背后的想法是比较LinkedList和ArrayList的性能。 如果我执行以下操作,那么只有一半的元素会被删除…为什么呢? 亲切的问候阿里安 问题答案: 发生这种情况是因为您要通过删除来更改索引。如果删除元素0,则元素1现在变为元素0。现在,当您下次删除1时

  • 问题内容: 我有这个: 有没有一种方法可以获取更新的列表作为结果,而不是就地更新原始列表? 问题答案: 我得到的最短信息:

  • 返回数组中所有 val 的索引。 如果 val 从不出现,则返回 [] 。 使用 Array.forEach() 循环元素和 Array.push() 来存储匹配元素的索引。 返回索引数组。 const indexOfAll = (arr, val) => { const indices = []; arr.forEach((el, i) => el === val && indices.

  • 我有这个: 有没有办法可以得到更新后的列表,而不是就地更新原始列表?

  • 改变原始数组,过滤出指定的值。 返回删除的元素。 使用 Array.filter() 和 Array.includes() 来剔除指定的值。使用 Array.length = 0 将数组中的长度重置为零, 并且通过 Array.push() 只使用 pulled 值重新填充数组。使用 Array.push() 来跟踪 pulled 值。 const pullAtValue = (arr, pull

  • 我正在尝试编写一种方法,删除每组4个元素中的第一个、第二个和第三个元素。它似乎根本不起作用。有人能帮忙吗?