Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
这道题要产生一个数组的所有排列情况,可以使用递归的思想,一个一个元素往里加,直到达到个数要求。使用flag来标记是否添加过。和我最近在做的蛋白质搜索引擎中加修饰的情况很类似,实现如下:
class Solution {
public:
void work(vector<vector<int> >& ans, vector<int>& tmp, vector<int>& nums, vector<int>& flag)
{
if (tmp.size() == nums.size()) {
ans.push_back(tmp);
}
else {
for (int i = 0; i < flag.size(); i++) {
if (flag[i] == 1) {
vector<int> next = tmp;
next.push_back(nums[i]);
flag[i] = 0;
work(ans, next, nums, flag);
flag[i] = 1;
}
}
}
}
vector<vector<int> > permute(vector<int>& nums)
{
vector<int> flag(nums.size(), 1);
vector<vector<int> > ans;
vector<int> tmp;
work(ans, tmp, nums, flag);
return ans;
}
};
本代码提交AC,用时21MS。
二刷。其实上述代码中不需要复制一个next数组的,代码如下:
class Solution {
private:
void DFS(const vector<int>& nums, vector<int>& visited, vector<int>& candidate, vector<vector<int> >& ans)
{
if (candidate.size() == nums.size()) {
ans.push_back(candidate);
return;
}
for (int i = 0; i < nums.size(); ++i) {
if (visited[i] == 0) {
visited[i] = 1;
candidate.push_back(nums[i]);
DFS(nums, visited, candidate, ans);
visited[i] = 0;
candidate.pop_back();
}
}
}
public:
vector<vector<int> > permute(vector<int>& nums)
{
vector<int> visited(nums.size(), 0), candidate;
vector<vector<int> > ans;
DFS(nums, visited, candidate, ans);
return ans;
}
};
本代码提交AC,用时9MS,击败79%。
还可以不需要visited和candidate数组,用交换的思路,代码如下:
class Solution {
private:
void DFS(vector<int>& nums, vector<vector<int> >& ans, int start)
{
if (start == nums.size()) {
ans.push_back(nums);
return;
}
for (int i = start; i < nums.size(); ++i) {
swap(nums[i], nums[start]);
DFS(nums, ans, start + 1);
swap(nums[i], nums[start]);
}
}
public:
vector<vector<int> > permute(vector<int>& nums)
{
vector<vector<int> > ans;
DFS(nums, ans, 0);
return ans;
}
};
本代码提交AC,用时16MS。
Pingback: LeetCode Permutations II | bitJoy > code
Pingback: LeetCode Permutation Sequence | bitJoy > code
Pingback: LeetCode Combinations | bitJoy > code