Topic:
Given A collection of distinct numbers, return all possible permutations.
For example,
[following] has the permutations:
[1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
Solutions:
Idea 1:
It is easier to think of the number of the first digit and then the whole arrangement. Using recursive thinking, each recursion is fixed first.
Code:
vector<vector<int>>Permute ( vector<int>& Nums) {intN = Nums.size (); vector<vector<int>>Resultif(N = =1) {Result.push_back (nums);returnResult } vector<int>Temp//temporary storage of the remaining nums vector<vector<int>>M_temps; for(inti =0; i < n;i++) {temp = Nums; Temp.erase (Temp.begin () +i);//Delete the number labeled I, then make the rest of the full arrangement, this number is inserted into the beginningM_temps = Permute (temp);//The rest of the full arrangement for(intj =0; J < M_temps.size (); j + +) { vector<int>s = m_temps[j];//Get each full arrayS.insert (S.begin (), nums[i]);//Insert the number of deletions into the initial positionResult.push_back (s); } }returnResult }
Idea 2:
This idea is more common, in turn, the number of each digit in turn and the number in the back position to exchange.
Code:
voidPerm vector<vector<int>>& result, vector<int>Numsinti) {if(i = = Nums.size ()-1) Result.push_back (nums); for(intj = i; J < Nums.size (); j + +) {swap (nums[i],nums[j]); Perm (result,nums,i+1); Swap (nums[i],nums[j]); } } vector<vector<int>>Permute ( vector<int>& Nums) {intN = Nums.size (); vector<vector<int>>Result Perm (Result,nums,0);returnResult }
[Leetcode]046-permutations