[Leetcode]046-permutations

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.