您的位置:首页 > 其它

[LintCode] Permutations

2015-05-22 22:34 162 查看
http://www.lintcode.com/en/problem/permutations/#

Given a list of numbers, return all possible permutations.

Example

For nums =
[1,2,3]
, the permutations are:

[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]



求全排列,可以使用DFS来解决,来看代码:



class Solution {
public:
/**
* @param nums: A list of integers.
* @return: A list of permutations.
*/
vector<vector<int> > permute(vector<int> nums) {
// write your code here
vector<vector<int>> paths;
if (nums.empty()) {
return paths;
}

vector<int> index;
vector<int> path;
permuteHelper(nums, index, path, paths);
return paths;

}

private:
void permuteHelper(const vector<int> &nums,
vector<int> &index,
vector<int> &path,
vector<vector<int>> &paths) {
if (path.size() == nums.size()) {
paths.push_back(path);
return;
}

for (int ix = 0; ix < nums.size(); ix++) {
if (find(index.begin(), index.end(), ix) == index.end()) {
index.push_back(ix);
path.push_back(nums[ix]);
permuteHelper(nums, index, path, paths);
index.pop_back();
path.pop_back();
}
}
}
};


实际上,观察某数是否已经访问过,不必使用一个vector,因为在vector中看一个数有没有访问过,需要o(n)的时间复杂度,此处完全可以用一个hashset来代替,看以下代码:

class Solution {
public:
/**
* @param nums: A list of integers.
* @return: A list of permutations.
*/
vector<vector<int> > permute(vector<int> nums) {
// write your code here
vector<vector<int>> paths;
if (nums.empty()) {
return paths;
}

unordered_set<int> index;
vector<int> path;
permuteHelper(nums, index, path, paths);
return paths;
}

private:
void permuteHelper(const vector<int> &nums,
unordered_set<int> &index,
vector<int> &path,
vector<vector<int>> &paths) {
if (path.size() == nums.size()) {
paths.push_back(path);
return;
}

for (int ix = 0; ix < nums.size(); ix++) {
if (index.count(ix) == 0) {
index.insert(ix);
path.push_back(nums[ix]);
permuteHelper(nums, index, path, paths);
index.erase(ix);
path.pop_back();
}
}
}
};


能不能更进一步?这边完全可以使用一个数组来模拟hashset,来看代码:

class Solution {
public:
/**
* @param nums: A list of integers.
* @return: A list of permutations.
*/
vector<vector<int> > permute(vector<int> nums) {
// write your code here
vector<vector<int>> paths;
if (nums.empty()) {
return paths;
}

bool *visited = new bool[nums.size()]();
vector<int> path;
permuteHelper(nums, visited, path, paths);
return paths;
}

private:
void permuteHelper(const vector<int> &nums,
bool *visited,
vector<int> &path,
vector<vector<int>> &paths) {
if (path.size() == nums.size()) {
paths.push_back(path);
return;
}

for (int ix = 0; ix < nums.size(); ix++) {
if (visited[ix] == false) {
visited[ix] = true;
path.push_back(nums[ix]);
permuteHelper(nums, visited, path, paths);
visited[ix] = false;
path.pop_back();
}
}
}
};


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: