I was working on the problem Permutations on LeetCode. I tried two identical solutions except that the first one uses Java stream and the other does not. Both got accepted, but the first one took 38ms and the second one's runtime is negligible (0 ms). I wonder what are the causes of such a dramatic difference. Following is my code
solution 1
import java.util.*;
import java.util.stream.Collectors;
class Solution {
List<List<Integer>> ans = new LinkedList<>();
private void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
private void permutation(int[] nums, int pos) {
if (pos == nums.length - 1) {
// List<Integer> temp = new LinkedList<>();
// for (int n : nums)
// temp.add(n);
// ans.add(temp);
ans.add(Arrays.stream(nums).boxed().collect(Collectors.toList()));
}
for (int i = pos; i < nums.length; i++) {
swap(nums, i, pos);
permutation(nums, pos + 1);
swap(nums, i, pos);
}
}
public List<List<Integer>> permute(int[] nums) {
permutation(nums, 0);
return ans;
}
}
solution 2
import java.util.*;
import java.util.stream.Collectors;
class Solution {
List<List<Integer>> ans = new LinkedList<>();
private void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
private void permutation(int[] nums, int pos) {
if (pos == nums.length - 1) {
List<Integer> temp = new LinkedList<>();
for (int n : nums)
temp.add(n);
ans.add(temp);
// ans.add(Arrays.stream(nums).boxed().collect(Collectors.toList()));
}
for (int i = pos; i < nums.length; i++) {
swap(nums, i, pos);
permutation(nums, pos + 1);
swap(nums, i, pos);
}
}
public List<List<Integer>> permute(int[] nums) {
permutation(nums, 0);
return ans;
}
}
Thank you for your time.