题目:
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]
.
思路:
1、参考求nextPermutation下一个排列:http://blog.csdn.net/u012243115/article/details/42673905,求n! 次即可。
2、:stl 库有这个函数next_permutation,但是nextPermutation不能循环,比如说3 2 1后就没了。
3、DFS .详情参考:http://www.cnblogs.com/fightformylife/p/4120381.html 。
代码1:
class Solution {
public:
vector<vector<int> > permute(vector<int> &num)
{
int len = num.size();
vector<vector<int> > result;
result.push_back(num);
if(len == 0)
return result;
int count = 1;
while(len > 0)
{
count *= len;
len--;
}
for(int i = 1 ; i < count ; i++)
{
nextPermutation(num);
result.push_back(num);
}
return result;
}
void nextPermutation(vector<int> &num)
{
if(num.size() <= 1)
return;
int index1 = -1,index2;
//从后向前找到开始递减的数的位置,放入index1,比如 5 5 2 4 7 6 3,定位到4,则index1 = 3
for(int i = num.size()-2 ; i >= 0 ; i--)
{
if(i >=0 && num[i] < num[i+1])
{
index1 = i;
break;
}
}
//如果不存在递减的数,即从后向前一直递增,则直接把数字翻转一下即可,比如数组 3 2 1
if(index1 == -1)
{
reverse(num.begin(),num.end());
return;
}
//从后向前找到第一个比num[index1]大的数
for(int j = num.size()-1 ; j > index1 ; j--)
{
if(num[j] > num[index1])
{
index2 = j;
break;
}
}
//交换num[index1]和num[index2]
swap(num[index1] , num[index2]);
//对index1后面的数翻转一下即可
reverse(num.begin()+index1+1,num.end());
return;
}
};
代码2:
class Solution {
public:
vector<vector<int> > permute(vector<int> &num)
{
int len = num.size();
vector<vector<int> > result;
sort(num.begin(),num.end());
result.push_back(num);
if(len == 0)
return result;
int count = 1;
while(len > 0)
{
count *= len;
len--;
}
for(int i = 1 ; i < count ; i++)
{
next_permutation(num.begin(), num.end());
result.push_back(num);
}
return result;
}
};
代码3:
class Solution {
public:
vector<vector<int> > result;
vector<int> path;
vector<vector<int>> permute(vector<int>& nums)
{
int len = nums.size();
vector<int> visited(len , 0); //标记当前数字是否插入到path中
dfs(0 , len , nums , visited);
return result;
}
void dfs(int depth , int &len , vector<int> &nums , vector<int> &visited)
{
if(depth == len)
{
result.push_back(path);
}
for(int i = 0 ; i < len ; i++)
{
if(visited[i] == 0)
{
visited[i] = 1;
path.push_back(nums[i]);
dfs(depth + 1 , len , nums , visited);
visited[i] = 0;
path.pop_back();
}
}
}
};
代码4:
这个DFS只适用于不相同的数。
class Solution {
public:
vector<vector<int> > permute(vector<int> &num)
{
vector<vector<int> > result;
DFS(num,0,result);
return result;
}
void DFS(vector<int> &num , int begin , vector<vector<int> > &result)
{
if(begin == num.size())
{
result.push_back(num);
return;
}
for(int i = begin ; i < num.size() ; i++)
{
swap(num[begin],num[i]);
DFS(num,begin+1,result);
swap(num[i],num[begin]);
}
}
};