a***e 发帖数: 413 | 1 【 以下文字转载自 JobHunting 讨论区 】
发信人: abcee (abcee), 信区: JobHunting
标 题: Re: 请问大牛们leetcode上的Permutations II
发信站: BBS 未名空间站 (Fri Jun 13 18:00:00 2014, 美东)
再问一下 , 对于无重复的permutation, 这个答案好理解。但怎么改来处理有重复数
的问题呢?
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].
vector > permute(vector& num) {
sort(num.begin(), num.end());
vector> result;
vector path;
dfs(num, path, result);
return result;
}
private:
void dfs(const vector& num, vector &path,vector > &
result) {
if (path.size() == num.size()) {
result.push_back(path);
return;
}
for (auto i : num) {
auto pos = find(path.begin(), path.end(), i);
if (pos == path.end()) {
path.push_back(i);
dfs(num, path, result);
path.pop_back();
}
}
}
For the following question,
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].
怎样才能处理有重复数字的情况?多谢! |
|