Permutations - Python Solution

1. Introduction

The "Permutations" problem is a fundamental combinatorial problem in computer science and is frequently encountered in coding interviews. It involves finding all possible arrangements (permutations) of a given set of distinct integers. This problem is a great exercise in understanding recursion and backtracking concepts.

Problem

Given an array nums of distinct integers, the task is to return all possible permutations of the array. The permutations can be returned in any order.

2. Solution Steps

1. Understand that a permutation involves arranging all the elements of the array in every possible order.

2. Utilize a recursive approach to generate permutations.

3. Swap each element with itself and all following elements, and then recurse for the rest of the array.

4. Backtrack after each recursive call by swapping the elements back to their original position.

5. When the base case is reached (i.e., the end of the array), add the current permutation to the result.

3. Code Program

```Python
def permute(nums):
    def backtrack(start):
        # Base case: if the start index reaches the end of the array
        if start == len(nums):
            res.append(nums[:])
            return
        # Swap the current element with the rest and recurse
        for i in range(start, len(nums)):
            nums[start], nums[i] = nums[i], nums[start]  # swap
            backtrack(start + 1)
            nums[start], nums[i] = nums[i], nums[start]  # backtrack

    res = []
    backtrack(0)
    return res

# Testing the function with examples
print(permute([1, 2, 3]))
print(permute([0, 1]))
print(permute([1]))

Output:

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
[[0, 1], [1, 0]]
[[1]]

Explanation:

1. Recursive Function: The backtrack function is used to generate permutations. It takes a start index as an argument.

2. Swapping: In each recursive call, the function swaps the element at the start index with each element that comes after it.

3. Recursion: After swapping, it recursively calls itself with the next start index.

4. Base Case: When start equals the length of nums, it means a full permutation is formed, which is then added to the result.

5. Backtracking: After each recursive call, the elements are swapped back to their original position before moving to the next iteration.

6. Result: The function returns an array of all possible permutations.


Comments