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());**
}