LeetCode Permutations II

Source: Internet
Author: User

LeetCode Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2]Have the following unique permutations:
[1,1,2],[1,2,1], And[2,1,1].

Ask for all sequences that are not repeated.

Train of Thought: dfs, but note that if deduplication: after sorting, you can set a vis for each number to indicate whether access has been made, when two adjacent numbers are the same and the previous one has been accessed, this number can be used to avoid duplication.

class Solution {public:    int vis[110], a[110];    vector
 
   > ans;    void dfs(int cur, int n, vector
  
    &num) {        if (cur == n) {            vector
   
     tmp;            for (int i = 0; i < n; i++)                 tmp.push_back(a[i]);            ans.push_back(tmp);            return;        }        for (int i = 0; i < n; i++)             if (!vis[i]) {                if (i != 0 && num[i] == num[i-1] && vis[i-1]) continue;                vis[i] = 1;                a[cur] = num[i];                dfs(cur+1, n, num);                vis[i] = 0;            }    }    vector
    
      > permuteUnique(vector
     
       &num) {        sort(num.begin(), num.end());        ans.clear();        memset(vis, 0, sizeof(vis));        dfs(0, num.size(), num);        return ans;    }};
     
    
   
  
 




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.