public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>();
backtrack(list, "", 0, 0, n);
return list;
}
public void backtrack(List<String> list, String str, int open, int close, int max){
if(str.length() == max*2){
list.add(str);
return;
}
if(open < max)
backtrack(list, str+"(", open+1, close, max);
if(close < open)
backtrack(list, str+")", open, close+1, max);
}
In the above code 'list' is a List of strings defined in generateParenthesis()
. In backtrack(list, "", 0, 0, n);
they don't store the value of list returned by backtrack()
but when the final list is returned in return list;
the value of list is as returned by backtrack()
My question is: why is the instance of 'list' variable created in generateParenthesis()
getting modified even though it is not a static variable and neither is the value returned by backtrack()
function is being stored in 'list' by using an assignment operation like list=backtrack(list, "", 0, 0, n);
?