LeetCode --- 46. Permutations

Source: Internet
Author: User

LeetCode --- 46. Permutations

Link: Permutations

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]. 

This question requires that a group of numbers be given to generate all the permutation and combination.

1. Recursive Arrangement

This is a problem of arrangement. The first thing we think of is recursion. Fix each element one by one to the first position, and recursively arrange the remaining elements. When the number of elements fixed to the front is equal to the length of the array, recursion ends.

Time Complexity: O (n !) (Number of results)

Space complexity: O (n !)

 1 class Solution 2 { 3 public: 4     vector
  
    > permute(vector
   
     &num) 5     { 6         vector
    
      > vvi; 7         permute(num, 0, vvi); 8         return vvi; 9     }10 private:11     void permute(vector
     
       &num, int i, vector
      
        > &vvi)12 {13 if(i == num.size())14 {15 vvi.push_back(num);16 return;17 }18 for(int j = i; j < num.size(); ++ j)19 {20 swap(num[i], num[j]);21 permute(num, i + 1, vvi);22 swap(num[i], num[j]);23 }24 }25 };
      
     
    
   
  
2. next_permutation

In fact, you can also use the next_permutation () function to gradually generate the next arrangement. Because next_permutation () returns false in the last arrangement, you can first sort the array and then call next_permutation () until it returns false.

Time Complexity: O (n !) (Number of results)

Space complexity: O (n !)

 1 class Solution 2 { 3 public: 4     vector
  
    > permute(vector
   
     &num) 5     { 6         sort(num.begin(), num.end()); 7          8         vector
    
      > vvi({num}); 9         while(next_permutation(num.begin(), num.end()))10             vvi.push_back(num);11         12         return vvi;13     }14 };
    
   
  

 

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.