A simple Golang solution in 22 ms


  • 0
    P
    func permuteUnique(nums []int) (result [][]int) {
        sort.Ints(nums)
        for goOn := true;goOn; nums, goOn = nextPermute(nums){
            result = append(result, nums)
        }
        return
    }
    
    func nextPermute(nums []int) ([]int, bool) {
        ret := make([]int, len(nums))
        copy(ret, nums)
        for i := len(nums) - 1; i > 0 ; i-- {
            if nums[i] > nums[i - 1] {
                for j := len(nums)-1; j >= i ; j-- {
                    if nums[j] > nums[i-1] {
                        ret[i-1], ret[j] = ret[j], ret[i-1]
                        sort.Ints(ret[i:])
                        return ret, true
                    }
                }
            }
        }
        return nil ,false
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.