Me and my friend were solving permutation question on leetcode and we came up with this below answer
func permute(nums []int) [][]int {
if len(nums) == 1 {
return [][]int{nums}
}
var result [][]int
for i, num := range nums {
tempans := permute(append(nums[:i], nums[i+1:]...))
for _, perm := range tempans {
result = append(result, append([]int{num}, perm...))
}
}
return result
}
the above function returns wrong answer
[[1,2,3],[1,3,3],[3,3,3],[3,3,3],[3,3,3],[3,3,3]]
But the code worked when we replaced permute(append(nums[:i], nums[i+1:]...))
with
remaining := append([]int{}, nums[:i]...)
remaining = append(remaining, nums[i+1:]...)
below is the final working code
func permute(nums []int) [][]int {
if len(nums) == 1 {
return [][]int{nums}
}
var result [][]int
for i, num := range nums {
remaining := append([]int{}, nums[:i]...)
remaining = append(remaining, nums[i+1:]...)
tempans := permute(remaining)
for _, perm := range tempans {
result = append(result, append([]int{num}, perm...))
}
}
return result
}
why what is the difference?