I was reading recursive solution of permutation in Java. Below is the code for the same.
class PermutationsRecursive {
public static List<List<Integer>> generatePermutations(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
generatePermutationsRecursive(nums, 0, new ArrayList<Integer>(), result);
return result;
}
private static void generatePermutationsRecursive(int[] nums, int index, List<Integer> currentPermutation, List<List<Integer>> result) {
if (index == nums.length) {
result.add(currentPermutation);
}
else {
// Create a new permutation by adding the current number at every position
for (int i = 0; i <= currentPermutation.size(); i++) {
List<Integer> newPermutation = new ArrayList<Integer>(currentPermutation);
newPermutation.add(i, nums[index]);
generatePermutationsRecursive(nums, index + 1, newPermutation, result);
}
}
}
public static void main(String[] args) {
List<List<Integer>> result = PermutationsRecursive.generatePermutations(new int[] { 1, 3, 5 });
System.out.print("Here are all the permutations: " + result);
}
}
Now the variable result declared as List<List<Integer>> result = new ArrayList<>()
in the generatePermutations
method is passed in next line in generatePermutationsRecursive
, and this function returns void
.
What puzzles me is that result variable declared in generatePermutations
and the result variable declared in definition of generatePermutationsRecursive
function are of different scope and yet the result variable is updated and gives the permutation of the set.
I wrote a sample program with similar approach but the variable y
was not updated and it gives me 0 which makes sense to me as the variable y
scope is different in both functions. But I couldn't understand the above code that how variable result was updated. Below is my sample code.
class Jewel {
public static int findNum(int x) {
int y = 0;
temp(x, y);
return y;
}
public static void temp(int x, int y) {
while (x > 0) {
y = y + 2;
x--;
temp(x,y);
}
}
}
public class HelloWorld {
public static void main(String[] args) {
Jewel j1 = new Jewel();
int result = j1.findNum(4);
System.out.println(result);
}
}