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]
. 排列组合的问题,不用考虑是否发生重复的情况,代码如下:
1 class Solution { 2 public: 3 vector> permute(vector & nums) { 4 memset(mark, 0, sizeof(mark)); 5 memset(cdds, 0, sizeof(cdds)); 6 dfs(0, nums.size(), nums); 7 return ret; 8 } 9 10 void dfs(int dep, int maxDep, vector & nums)11 {12 if(dep == maxDep){13 tmp.clear();14 for(int i = 0;i < maxDep; ++i)15 tmp.push_back(cdds[i]);16 ret.push_back(tmp);17 }else{18 for(int i = 0; i < maxDep; ++i){19 if(!mark[i]){20 mark[i] = true;21 cdds[dep] = nums[i];22 dfs(dep + 1, maxDep, nums);23 mark[i] = false;24 }25 }26 }27 }29 private:30 int cdds[100];31 bool mark[100];32 vector tmp;33 vector > ret;34 35 };