参数传递机制让我很困惑。我已经阅读了大量关于Is Java "pass-by-reference" or "pass-by-value"?等文章的文章。我知道他们通过价值传递它。但是,他们没有谈到一个案例:通过对象本身。
我在解决leetcode问题时遇到了这个问题。
生成括号
给定n对括号,编写一个函数来生成格式正确的括号的所有组合。
例如,给定n = 3,解集是:
“((()))”,“(()())”,“(())()”,“()(())”,“()()()”
还有一个递归代码
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);
}
}
}
我正在努力理解代码的作用,尤其是:
if(left < n){
helper(result, str + "(", left + 1, right, n);
}
if(right < n){
helper(result, str + ")", left, right + 1, n);
}
辅助方法的第二个参数是由字符串而不是字符串的变量名传递的,在这种情况下会发生什么?我想也许这是阻碍我理解代码的部分。谁能告诉我为什么这段代码有效?我真的花了很多时间在Java中读取参数传递机制和递归,但它仍然让我困惑。
非常感谢。
答案 0 :(得分:0)
Java中的基元是按值传递,但对象传递引用的副本。此处显示的此代码块的最后四行,3/4是花括号。你究竟想要了解什么?
因此,此代码基本上使用递归方法提供了一个字符串List。我不知道你对递归了解多少,但它基本上是在同一个方法中调用方法。一开始可能会让人感到困惑,但如果你能理解它,你可以编写漂亮而简短的代码。基本上这是在List结果中添加一个String。 left和right是当前String中左侧括号和右侧括号的数量。我对代码进行了评论,可能会帮助您更好地理解。
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>(); //The list that gets returned at the end of generateParenthesis method.
String str = new String(""); //Initialized string that contains nothing.
helper(result, str, 0, 0, n); //First call of helper method.
return result; //Final result gets returned to caller.
}
public void helper(List<String> result, String str, int left, int right, int n){
//If number of left parenthesis and number of right parenthesis is the number of parenthesis total we need, which in your example is 3 of each, add the string to the List result and return to the last caller.
if(left == n && right == n){
result.add(str);
return;
}
//If the number of left parenthesis is less than the number of right parenthesis, return to the last call of method.
if(left < right){
return;
}
//If the number of left parenthesis is less than the number of total required, add a left parenthesis to String str and incremement number of left parenthesis by one.
if(left < n){
helper(result, str + "(", left + 1, right, n); //call helper via recursion and make the new value of str = str+"(" and increment number of left parenthesis by 1.
}
//If number of right parenthesis is less than the number of total parenthesis required, add a right facing parenthesis to String str and increment number of right parenthesis by one.
if(right < n){
helper(result, str + ")", left, right + 1, n);
}
}