• [leetcode] Permutations II


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

    思路:

    含有重复数字的全排列,关键是去重。首先排序,重复的元素相邻。如果当前元素与之前元素相等,如果之前元素还未被访问,则当前元素不可访问。换句话说,当前元素与前一个元素相等,只有当前一个元素被访问时,当前元素才能被访问。从而实现了去重。

    题解:

    class Solution {
    public:
        vector<vector<int> > res;
        vector<int> tmp;
        void dfs(vector<int> &num, bool visited[], int index) {
            if(index==num.size()) {
                res.push_back(tmp);
                return;
            }
            for(int i=0;i<num.size();i++) {
                if(!visited[i]) {
                    if(i!=0 && num[i]==num[i-1] && !visited[i-1])
                        continue;
                    tmp.push_back(num[i]);
                    visited[i] = true;
                    dfs(num, visited, index+1);
                    visited[i] = false;
                    tmp.pop_back();
                }
            }
        }
        vector<vector<int> > permuteUnique(vector<int> &num) {
            int n = num.size();
            bool *visited = new bool [n];
            memset(visited, false, sizeof(bool)*n);
            sort(num.begin(), num.end());
            dfs(num, visited, 0);
            return res;
        }
    };
  • 相关阅读:
    samdump2获取虚拟机密码
    PHP执行cmd方法若干
    Aircrack-ng学习笔记之无AP破解WiFi密码
    Python基础:extend与append的区别
    Python基础:dictionary
    UVALive 3177 长城守卫
    UVALive 3902 网络
    UVA 11520 填充正方形
    UVALive 3635 分派
    UVALive 3971 组装电脑
  • 原文地址:https://www.cnblogs.com/jiasaidongqi/p/4155186.html
Copyright © 2020-2023  润新知