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]]
AC code:
class Solution {public: vector> permute(vector & nums) { vector > v; iteration(nums, v, 0); return v; } void iteration(vector & nums, vector >& v, int begin) { if (begin >= nums.size()) { v.push_back(nums); return; } for (int i = begin; i < nums.size(); ++i) { swap(nums[begin], nums[i]); iteration(nums, v, begin+1); swap(nums[begin], nums[i]); } }};
Runtime: 12 ms, faster than 42.11% of C++ online submissions for Permutations.