// Source : https://oj.leetcode.com/problems/permutations/ // Author : Hao Chen // Date : 2014-06-21 /********************************************************************************** * * 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]. * * **********************************************************************************/ #include #include #include #include using namespace std; /* { 1 2 3 } { 2 1 3 } { 3 2 1 } { 1 3 2 } { 2 3 1 } { 3 1 2 } */ /* * The algroithm - Take each element in array to the first place. * * For example: * * 0) initalization * * pos = 0 * [1, 2, 3] * * 1) take each element into the first place, * * pos = 1 * [1, 2, 3] ==> [2, 1, 3] , [3, 1, 2] * * then we have total 3 answers * [1, 2, 3], [2, 1, 3] , [3, 1, 2] * * 2) take each element into the "first place" -- pos * * pos = 2 * [1, 2, 3] ==> [1, 3, 2] * [2, 1, 3] ==> [2, 3, 1] * [3, 1, 2] ==> [3, 2, 1] * * then we have total 6 answers * [1, 2, 3], [2, 1, 3] , [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1] * * 3) pos = 3 which greater than length of array, return. * */ vector > permute(vector &num) { vector > vv; vv.push_back(num); if (num.size() <2){ return vv; } int pos=0; while(pos v = vv[i]; int t = v[j]; v[j] = v[pos]; v[pos] = t; vv.push_back(v); } } pos++; } return vv; } int main(int argc, char** argv) { int n = 3; if (argc>1){ n = atoi(argv[1]); } vector v; for (int i=0; i > vv; vv = permute(v); for(int i=0; i