首页 > 其他 > 详细

【Leetcode】Permutations II

时间:2014-03-20 06:50:43      阅读:582      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     vector<vector<int> > permuteUnique(vector<int> &num) {
 4         vector<vector<int> > result;
 5         sort(num.begin(), num.end());
 6         vector<bool> used(100, false);
 7         vector<int> path;
 8         dfs(num, path, used, result);
 9         return result;
10     }
11     
12     private:
13     void dfs(vector<int> &num, vector<int> &path, vector<bool> used, vector<vector<int>> &result) {
14         if (path.size() == num.size()) {
15             result.push_back(path);
16             return;
17         }
18         for (size_t i = 0; i < num.size(); ++i) {
19             if (used[i] == false && (i == 0 || num[i] > num[i - 1] || used[i - 1])) {
20                 path.push_back(num[i]);
21                 used[i] = true;
22                 dfs(num, path, used, result);
23                 used[i] = false;
24                 path.pop_back();
25             }
26         } 
27     }
28 };
View Code

上一题类似,因为数字可能不同需要的处理有:用一个表记录下各位数有没有被用过,当遇到相同数字的时候,只有排在它之前的相等的数字都被用过了才选它(相当于赋予了编号)。

【Leetcode】Permutations II,布布扣,bubuko.com

【Leetcode】Permutations II

原文:http://www.cnblogs.com/dengeven/p/3611084.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!