题目描述
解法一:permutations(Python)
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
return list(itertools.permutations(nums))
解法二:next_permute(C++)
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
do{
res.push_back(nums);
}while(next_permutation(nums.begin(), nums.end()));
return res;
}
};
解法三:回溯法
Python实现
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
def backtrack(nums, tmp):
if not nums:
res.append(tmp)
return
for i in range(len(nums)):
backtrack(nums[:i] + nums[i+1:], tmp + [nums[i]])
backtrack(nums, [])
return res
C++实现
class Solution {
public:
vector<vector<int>> res;
vector<vector<int>> permute(vector<int>& nums) {
vector<int> track;
vector<int> used(nums.size(), 0);
backtrace(nums, track, used);
return res;
}
void backtrace(vector<int>& nums, vector<int>& track, vector<int> used)
{
if (track.size() == nums.size())
{
res.push_back(track);
return;
}
for (int i = 0; i < nums.size(); i++)
{
if (used[i]) continue;
used[i] = 1;
track.push_back(nums[i]);
backtrace(nums, track, used);
track.pop_back();
used[i] = 0;
}
}
};