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)

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;
    }
};

Last updated