描述 Given a collection of distinct numbers, return all possible permutations.
For example, [1,2,3] have the following permutations:
[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]分析 递归,vecotr头尾first、last, 1. 当first指向last的前一个元素,一次排列完成,将此次排列结果存入二维vector。 2. 从first向last靠近,不断交换first和first至last上的元素。 3. 递归执行以上步骤。
代码
class Solution {public: vector<vector<int>> permute(vector<int>& nums) { vector<int> tmp; vector<vector<int>> result; permute(nums, nums.begin(), nums.end(), result); return result; } template <typename BidiIt> void permute(vector<int>& nums, BidiIt first, BidiIt last, vector<vector<int>> &result) { if (first == PRev(last)) { result.push_back(nums); } else { for (auto it = first; it != last; ++it) { swap(*it, *first); permute(nums, next(first), last, result); swap(*it, *first); } } }};新闻热点
疑难解答