46. Permutations

Problem:

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]
]

Solutions:

class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> ret;
        vector<int> path;
        helper(nums, 0, ret);
        return ret;
    }

    void helper(vector<int>& nums, int pos, vector<vector<int>>& ret) {
        if (nums.size() == pos) {
            ret.push_back(nums);
            return;
        }

        for (int i = pos; i < nums.size(); ++i) {
            swap(nums[pos], nums[i]);
            helper(nums, pos + 1, ret);
            swap(nums[pos], nums[i]);
        }
    }
};

results matching ""

    No results matching ""