【问题标题】:Return the updated ArrayList<Characters> after removing the specified element at the index删除索引处的指定元素后返回更新后的 ArrayList<Characters>
【发布时间】:2017-04-06 07:31:31
【问题描述】:

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

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

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

 findAllCombinations(sourceSet.remove(index), soFar + singleBracket, singleBracket); .

我确实通过了official documentation,但没有找到任何帮助。

感谢您的帮助,感谢您的宝贵时间。

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);

    }
}

【问题讨论】:

  • 可以选择在 2 行中完成吗?喜欢...{ sourceSet.remove(inex); findAllCombinations( sourceSet, soFar + singleBracket, ...
  • 感谢@Fildor 的洞察力,但是当代码从每个递归调用中出来时,我希望 sourceSet 保留 sourceSet 的原始值(它在递归调用中具有),这将在这种情况下不会发生。如果我错了,请纠正我,感谢任何建议。
  • 在这种情况下,无论如何,您需要以不同的方式进行操作。 sourceSet.remove(index) 将始终改变列表。您需要传递一个缺少索引处元素的副本。

标签: java arraylist character


【解决方案1】:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    相关资源
    最近更新 更多