学习Golang要努力,但是不要急!今天的这篇文章《为什么我的 Go 解决方案给出的结果与 C++ 不同?》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!
具有完全相同逻辑的两段代码给出了不同的解决方案。
go 中是否存在错误,或者我的代码中是否犯了一些愚蠢的错误?
这是一道 leetcode 问题 leetcode - permutations ii。
下面的 c++ 代码是某人编写的已接受的解决方案。
c++代码
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class solution {
public:
vector<vector<int>> permuteunique(vector<int> &num) {
sort(num.begin(), num.end());
vector<vector<int>>res;
helper(num, 0, num.size(), res);
return res;
}
void helper(vector<int> num, int start, int j, vector<vector<int> > &res) {
if (start == j-1) {
res.push_back(num);
return;
}
for (int i = start; i < j; i++) {
if (start == i || num[start] != num[i]) {
swap(num[start], num[i]);
helper(num, start + 1, j, res);
}
}
}
};
int main() {
solution s;
vector<int> nums({2,1,2});
vector<vector<int>> res = s.permuteunique(nums);
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res[i].size(); j++) {
cout << " " << res[i][j];
}
cout << endl;
}
}
我将上面的 c++ 代码翻译成下面的 golang 代码:
golang代码
package main
func permuteunique(nums []int) [][]int {
qsort(nums, 0, len(nums)-1)
res := make([][]int, 0, len(nums))
helper(&res, nums, 0)
return res
}
func helper(res *[][]int, nums []int, start int) {
if start == len(nums)-1 {
copied := make([]int, len(nums))
copy(copied, nums)
*res = append(*res, copied)
return
}
for i := start; i < len(nums); i++ {
if start == i || nums[start] != nums[i] {
nums[i], nums[start] = nums[start], nums[i]
helper(res, nums, start+1)
}
}
}
func main() {
nums := []int{2,1,2}
res := permuteunique(nums)
for i := 0; i < len(res); i++ {
for j := 0; j < len(res[0]); j++ {
print(" ", res[i][j]);
}
println()
}
}
func qsort(nums []int, low, high int) {
if low >= high {
return
}
i, j, pivot := low, high, nums[low]
for i < j {
for i < j && nums[j] >= pivot {
j--
}
nums[i] = nums[j]
for i < j && nums[i] <= pivot {
i++
}
nums[j] = nums[i]
}
nums[i] = pivot
qsort(nums, low, i-1)
qsort(nums, i+1, high)
}
输出
上面的代码都可以立即运行。以下是我的输出:
fondoger@localhost:Desktop$ g++ test.cpp -o app && ./app 1 2 2 2 1 2 2 2 1 fondoger@localhost:Desktop$ go run test.go 1 2 2 2 1 2 2 2 1 1 2 2
我尝试使用 goland ide 和 clion ide 调试了几个小时,但无法找出真相。
解决方案
试试这个:
func helper(res *[][]int, nums []int, start int) {
copied := make([]int, len(nums))
copy(copied, nums)
nums = copied;
if start == len(nums)-1 {
*res = append(*res, nums)
return
}
for i := start; i < len(nums); i++ {
if start == i || nums[start] != nums[i] {
nums[i], nums[start] = nums[start], nums[i]
helper(res, nums, start+1)
}
}
}
从一种语言移植到另一种语言时,您需要确保也“移植”隐式功能。在 c++ 解决方案中,调用 helper 函数语言时,将为每次迭代创建 nums 数组的副本。你没有克隆这个行为并得到不同的结果。我在 helper 函数的开头添加了应对 num ,效果很好。
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
