I have a code that finds permutations of numbers. Here is the C++ code
void premutate(std::vector<int> nums, int index)
{
if(index == nums.size())
{
ans.push_back(nums);
return;
}
for(int i = index; i<nums.size(); i++)
{
std::swap(nums[i], nums[index]);
premutate(nums, index+1);
std::swap(nums[i], nums[index]);
}
}
int main()
{
std::vector<int> v = {1,2,3};
premutate(v, 0);
for(std::vector<int> v: ans)
{
for(int x: v)
{
std::cout << x << " ";
}
std::cout << "\n";
}
}
Above code gives the following output -
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
3 1 2
And this is Okay. But when I translate this to a Java Code, which goes like this -
public ArrayList<ArrayList<Integer>> li = new ArrayList<ArrayList<Integer>>();
public void helper(ArrayList<Integer> al, int index) {
if(index == al.size()) {
li.add(al);
return;
}
for(int i = index; i<al.size(); i++) {
Collections.swap(al, i ,index);
helper(al, index+1);
Collections.swap(al, i, index);
}
}
public ArrayList<ArrayList<Integer>> permute(ArrayList<Integer> A) {
helper(A, 0);
return li;
}
My output is like this -
[[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
Please ignore the formatting of output, but see how the list of numbers is same in in Java, but not in C++ output
I have been coding in C++ for past 3 years, and I am new to Java. What am I doing wrong ???