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]
.印出所有的排列組合,使樣回朔法來跑
用一個boo;陣列來記錄那些數字用過了
接著丟給下一個去紀錄
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | class Solution { public: void find(vector<vector<int>> &ans, vector<int> ¤t, vector<int> &nums, bool *use){ if(current.size() == nums.size()){ ans.push_back(current); return ; } for(int i=0;i<nums.size();i++){ if(use[i]==false){ current.push_back(nums[i]); use[i]=true; find(ans,current,nums,use); current.pop_back(); use[i]=false; } } } vector<vector<int>> permute(vector<int>& nums) { int size=nums.size(); bool use[size]={0}; vector<vector<int>> ans; vector<int> current; find(ans,current,nums,use);//not &use //for(int i=0;i<size;i++)use[i]=false; return ans; } }; |
--------------------
旋轉的方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | class Solution { public: vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> res; create(nums,res,0); return res; } void create(vector<int>& nums,vector<vector<int>> &res,int n) { if(n==nums.size()-1) res.push_back(nums); else { for(int i=n;i<nums.size();i++) { swap(nums[i],nums[n]); create(nums,res,n+1); swap(nums[i],nums[n]); } } } void swap(int &a,int &b) { int tmp=a; a=b; b=tmp; } }; |
沒有留言:
張貼留言