我想的办法和之前实现combination sum 是一个思路;用的是回溯法,若有一个数组[1,2,3,4];则共有4!种排序;
于是外层进行4!循环,然后依次遍历这个数组;第一次是1,push进一个vector,然后,进行递归,将剩下的[2,3,4]也执行同样的操作,即首先将2push进vector,再将[3,4]进行递归,当[3,4]递归结束,将2pop_back出来,然后,替换2和3的位置,数组就变成了[3,2,4],然后将3push进去,剩下的[2,4]进行递归,当这次递归结束,将2和3换回来,数组又变成了[2,3,4],然后将2和4替换,再进行push,递归。。。。
class Solution {
public:
void sswap(vector<vector<int>> &res, vector<int> &arr, int index, int size, vector<int> temp)
{
if (temp.size() == size) res.push_back(temp);
else {
for (int i = index; i < arr.size(); ++i)
{
swap(arr[i], arr[index]);
temp.push_back(arr[index]);
sswap(res,arr, index + 1, size, temp);
temp.pop_back();
swap(arr[i], arr[index]);
}
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> result;
vector<int> temp;
sswap(result, nums, 0, nums.size(), temp);
return result;
}
};
这是别人的办法,和实现的c++版本,提供了一种不同的思路;但实现的时间复杂度上就大了很多。
the basic idea is, to permute n numbers, we can add the nth number into the resulting List<List<Integer>>
from the n-1 numbers, in every possible position.
For example, if the input num[] is {1,2,3}: First, add 1 into the initial List<List<Integer>>
(let's call it "answer").
Then, 2 can be added in front or after 1. So we have to copy the List in answer (it's just {1}), add 2 in position 0 of {1}, then copy the original {1} again, and add 2 in position 1. Now we have an answer of {{2,1},{1,2}}. There are 2 lists in the current answer.
Then we have to add 3. first copy {2,1} and {1,2}, add 3 in position 0; then copy {2,1} and {1,2}, and add 3 into position 1, then do the same thing for position 3. Finally we have 2*3=6 lists in answer, which is what we want.
vector<vector<int>> permute(vector<int>& nums) {
vector<int> curr;
vector<vector<int> > ans;
if(nums.size()==0)
return ans;
curr.push_back(nums[0]); // insert first element
ans.push_back(curr); // insert the vector with first element
for(int i=1;i<nums.size();i++) // start from 2nd element of list
{
vector<vector<int> > new_ans;
for(int j=0;j<=i;j++) // insert nums[i] at 0->i position in result list
{
for(auto itr = ans.begin();itr!=ans.end();itr++) // get every list from ans to insert num[i]
{
vector<int> curr1(*itr); // copy the list into new vector
curr1.insert(curr1.begin()+j,nums[i]); // insert num[i] at pos j
new_ans.push_back(curr1); // insert new list into new ans
}
}
ans = new_ans; // copy ans
}
return ans;
}