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]
.
解題代碼如下:
class Solution { public: vector> result; public: vector > permute(vector &num) { int length=num.size(); perm(num,0,length-1); return result; } void perm(vector &num,int k,int m){ if(k==m) result.push_back(num); for(int i=k;i<=m;i++){ swap(num[k],num[i]); perm(num,k+1,m); swap(num[k],num[i]); } } void swap(int &a,int &b){ int temp=a; a=b; b=temp; } };