The parameter passing mechanism confuses me a lot. I've read tons of articles about that such as Is Java "pass-by-reference" or "pass-by-value"?. I know they pass it by value. However, they did not talk about one case: passing by the object itself.
I ran into this problem while solving a leetcode question.
Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
And there is an recursion code
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
String str = new String("");
helper(result, str, 0, 0, n);
return result;
}
public void helper(List<String> result, String str, int left, int right, int n){
if(left == n && right == n){
result.add(str);
return;
}
if(left < right){
return;
}
if(left < n){
helper(result, str + "(", left + 1, right, n);
}
if(right < n){
helper(result, str + ")", left, right + 1, n);
}
}
}
I am struggling understanding what the code does, especially:
if(left < n){
helper(result, str + "(", left + 1, right, n);
}
if(right < n){
helper(result, str + ")", left, right + 1, n);
}
The second parameter of the helper method is passed by a string instead of a variable name of the string, what would happen in this circumstance? I think maybe that is the part which hinders me understanding the code. Could anyone tell me why does this code work? I really spend a lot of time reading parameter passing mechanism and recursion in Java but it still confuses me.
Thanks a lot.