[英]Pass by reference and passing without reference in function
i was solving this problem: https://leetcode.com/problems/permutations-ii/我正在解决这个问题: https://leetcode.com/problems/permutations-ii/
here is my working solution:这是我的工作解决方案:
class Solution {
public:
vector<vector<int>> output;
void swap(vector<int>& nums, int index, int i){
int temp=nums[index];
nums[index]=nums[i];
nums[i]=temp;
return;
}
void helper(vector<int> nums, int index){ //here it is normally passed
if(index==nums.size()){
output.push_back(nums);
return;
}
for(int i=index; i<nums.size(); i++){
if(i!=index && nums[i]==nums[index]){continue;}
swap(nums, i, index);
helper(nums, index+1);
// swap(nums, i, index); //commented and used only with passed by reference
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
int size = nums.size();
sort(begin(nums) ,end(nums));
helper(nums, 0);
return output;
}
};
and then this is the solution in which i am passing by reference and swapping while backtracking:然后这是我在回溯时通过引用传递和交换的解决方案:
class Solution {
public:
vector<vector<int>> output;
void swap(vector<int>& nums, int index, int i){
int temp=nums[index];
nums[index]=nums[i];
nums[i]=temp;
return;
}
void helper(vector<int> &nums, int index){ //here nums is passed by reference
if(index==nums.size()){
output.push_back(nums);
return;
}
for(int i=index; i<nums.size(); i++){
if(i!=index && nums[i]==nums[index]){continue;}
swap(nums, i, index);
helper(nums, index+1);
swap(nums, i, index); //backtrack
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
int size = nums.size();
sort(begin(nums) ,end(nums));
helper(nums, 0);
return output;
}
};
But this solution does not apppear to be working fine.但是这个解决方案似乎不能正常工作。 Can anyone please explain why there is a difference between the two?
谁能解释一下为什么两者之间有区别?
In short - when you pass by reference, changes you make to the object inside your helper are applied to the original object.简而言之 - 当您通过引用传递时,您对助手内部的 object 所做的更改将应用于原始 object。 When you pass a copy ( like the original solution did) any changes you make will be applied to the copy and not the original.
当您传递副本时(就像原始解决方案所做的那样),您所做的任何更改都将应用于副本而不是原件。
In your solution, you pass a reference to a vector
into the helper function, inside of which - you call push_back()
on that reference - which means the original vector
gets bigger, and this is why your solution gives a result which is longer than expected.在您的解决方案中,您将对
vector
的引用传递给帮助程序 function,其中 - 您在该引用上调用push_back()
- 这意味着原始vector
变得更大,这就是为什么您的解决方案给出的结果比预期的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.