Leetcode 第 47 题,有重复数字的排列数,原题地址。
我对照着大佬写的 C++代码,自己写了一份 Golang 代码,运行结果总是不一致。
为了解决这个 bug,我专门下载了 goland 和 clion 两个 IDE,Golang 和 C++两边对照着调试,单步调试了好几个小时,还是找不到问题出在哪里。
我单步调试发现了一点点线索,在进行若干个递归步骤后,go 代码会从某行直接跳到下面的某行,没有执行中间的代码(在源码中通过注释标出)。
下面的两段代码都是直接可运行的代码,特地恳请大佬们帮忙 Debug !
代码比较简单,不需要理解解题步骤,大佬们肉眼对照找一下区别就好了。
感激不尽!
Golang 代码
package main
/*
 * @lc app=leetcode id=47 lang=golang
 *
 * [47] Permutations II
 */
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)
}
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;
    }
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.