Given a collection of 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]
, and [3,2,1]
.
思路:这题和string permutation差不多,依旧是枚举互换的位置。
1 class Solution { 2 public: 3 void permuteRecur(vector<vector<int> >& res, int st_loc, vector<int>& aim) 4 { 5 if (st_loc >= aim.size()) 6 res.push_back(aim); 7 else 8 { 9 for (int i = st_loc, n = aim.size(); i < n; i++) 10 { 11 swap(aim[st_loc], aim[i]); 12 permuteRecur(res, st_loc + 1, aim); 13 swap(aim[st_loc], aim[i]); 14 } 15 } 16 } 17 vector<vector<int>> permute(vector<int>& nums) { 18 vector<vector<int> > res; 19 permuteRecur(res, 0, nums); 20 return res; 21 } 22 };
原文:http://www.cnblogs.com/fenshen371/p/4922923.html