Problem Description:
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: void swap(int &a,int &b) { int temp=a; a=b; b=temp; } void permutations(vectornum,int begin,vector &permutation,vector > &res) { if(begin==num.size()) { res.push_back(permutation); return; } for(vector ::size_type index=begin;index!=num.size();++index) { swap(num[begin],num[index]); permutation.push_back(num[begin]); permutations(num,begin+1,permutation,res); permutation.pop_back(); swap(num[begin],num[index]); } } vector > permute(vector &num) { vector > res; if(num.empty()) return res; vector permutation; permutations(num,0,permutation,res); return res; } };