-1

I am working on the N Queens problem and the Generate Parentheses problem.

When you want a List<List<Integer>> as the result, and you want to add the List<Integer> to it, you need to do a deep copy right? Like result.add(new ArrayList<Integer>(cur))

But when you want a List<String> as an result, you can do result.add(sb.toString()). Why a deep copy isn't needed for adding stringbuilder.toString to a list?

Thank you for your time

The following is part of the code. They are the base case of their recursion function.

N Queens:

 public void helper(int n, List<Integer> cur, List<List<Integer>> result){
    if (cur.size() == n){
      **result.add(new ArrayList<Integer>(cur));**
      return;
    }

Generate Parentheses:

 private void helper(int n, StringBuilder sb, int left, int right, List<String> result) {
    if (sb.length() == n * 2){
      **result.add(sb.toString());**
    }
khelwood
  • 55,782
  • 14
  • 81
  • 108

1 Answers1

0

You cannot achieve deep copy in Java itself, you have to implement it manually if you want to.

But with immutable fields in Java, copy is always considered as deep copy. We're talking about primitives: int, byte, .. and String.

Nia Nia
  • 11
  • 1