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] ]
求数组的全排列
C++:
1 class Solution { 2 public: 3 vector<vector<int>> permute(vector<int>& nums) { 4 vector<vector<int>> permutes ; 5 vector<int> permute ; 6 vector<bool> visit(nums.size() , false) ; 7 backtracking(nums,permutes,permute,visit) ; 8 return permutes ; 9 } 10 11 void backtracking(vector<int>& nums ,vector<vector<int>>& permutes,vector<int>& permute,vector<bool>& visit){ 12 if (permute.size() == nums.size()){ 13 permutes.push_back(permute) ; 14 return ; 15 } 16 for(int i = 0 ; i < nums.size() ; i++){ 17 if (visit[i]){ 18 continue ; 19 } 20 visit[i] = true ; 21 permute.push_back(nums[i]) ; 22 backtracking(nums,permutes,permute,visit) ; 23 permute.pop_back() ; 24 visit[i] = false ; 25 } 26 } 27 };