> For the complete documentation index, see [llms.txt](https://soumyajit4419.gitbook.io/ds-algo/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://soumyajit4419.gitbook.io/ds-algo/recursion-and-backtracking/22.permutations.md).

# 7.Permutations

Given a collection of **distinct** integers, return all possible permutations.

```
Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
```

## Solution: (Backtracking)

```cpp
class Solution
{
public:
    void swapValues(vector<int> &nums, vector<vector<int>> &v, int start, int end)
    {
      
        if (start == end)
        {
            v.push_back(nums);
            return;
        }

        for (int i = start; i <= end; i++)
        {
            swap(nums[start], nums[i]);
            swapValues(nums, v, start + 1, end);
            swap(nums[start], nums[i]);
        }
        return;
    }

    vector<vector<int>> permute(vector<int> &nums)
    {
        vector<vector<int>> v;
        swapValues(nums, v, 0, nums.size() - 1);
        return v;
    }
};
```
