[LeetCode] 47. Permutations II 全排列 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],
  [2,1,1]
]

46. Permutations 的拓展,这题数组含有重复的元素。解法和46题,主要是多出处理重复的数字。

先对nums排序,使得相同的元素排在一起。新建一个大小与nums相同visited数组,用来标记在本次DFS读取中,位置i的元素是否已经被添加。

如果当前的数与前一个数相等,并且前一个数未被添加到list中,则可跳过这个数。

 

C++:

class Solution {
public:
    vector<vector<int> > permuteUnique(vector<int> &num) {
        vector<vector<int> > res;
        vector<int> out;
        vector<int> visited(num.size(), 0);
        sort(num.begin(), num.end());
        permuteUniqueDFS(num, 0, visited, out, res);
        return res;
    }
    void permuteUniqueDFS(vector<int> &num, int level, vector<int> &visited, vector<int> &out, vector<vector<int> > &res) {
        if (level >= num.size()) res.push_back(out);
        else {
            for (int i = 0; i < num.size(); ++i) {
                if (visited[i] == 0) {
                    if (i > 0 && num[i] == num[i - 1] && visited[i - 1] == 0) continue;
                    visited[i] = 1;
                    out.push_back(num[i]);
                    permuteUniqueDFS(num, level + 1, visited, out, res);
                    out.pop_back();
                    visited[i] = 0;
                }
            }
        }
    }
};

  

类似题目:

[LeetCode] 46. Permutations 全排列

[LeetCode] 31. Next Permutation 下一个排列

[LeetCode] 60. Permutation Sequence 序列排序

 

All LeetCode Questions List 题目汇总

 

posted @ 2018-03-13 06:35  轻风舞动  阅读(521)  评论(0编辑  收藏  举报