Problem statement Given a list, nums, of distinct numbers, return all possible unique permutations. Sample input
Sample output

[[1, 2, 1], [2, 1, 1], [1, 1, 2]] 
Solution In another post we showed how this problem can be solved iteratively. We can use the same technique but add a check to skip adding the number n to . . . Read more
Problem statement Given a list, nums, of distinct numbers, return all possible permutations. Sample input
Sample output

[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] 
Solution In another post we showed how this problem can be solved using a recursive technique by swapping. We stumbled upon a nice iterative solution that we thought might be worth . . . Read more
Problem statement Given a list, nums, of distinct numbers, return all possible permutations. Sample input
Sample output

[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] 
Solution We are using a technique called permutations by swapping. Full code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

class Solution(object): def swap(self, nums, i, j): tmp = nums[i] nums[i] = nums[j] nums[j] = tmp def solve(self, nums, i, result): if i == len(nums)1: result.append(list(nums)) return for j in range(i, len(nums)): self.swap(nums, i, j) self.solve(nums, i+1, result) self.swap(nums, i, j) def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ ans = [] self.solve(nums, 0, ans) return ans def main(): solution = Solution() print(solution.permute([1,2,3])) if __name__ == "__main__": main() 