题目描述
给定一个数字列表,返回其所有可能的排列。
样例1
输入:[1]
输出:
[
[1]
]
样例2
输入:[1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
解题思路
使用深度优先搜索算法。
使用 visited 数组记录某个数是否被放到 permutation 里了。
java题解
public class Solution {
/*
* @param nums: A list of integers.
* @return: A list of permutations.
*/
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> results = new ArrayList<>();
if (nums == null) {
return results;
}
dfs(nums, new boolean[nums.length], new ArrayList<Integer>(), results);
return results;
}
private void dfs(int[] nums,
boolean[] visited,
List<Integer> permutation,
List<List<Integer>> results) {
if (nums.length == permutation.size()) {
results.add(new ArrayList<Integer>(permutation));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i]) {
continue;
}
permutation.add(nums[i]);
visited[i] = true;
dfs(nums, visited, permutation, results);
visited[i] = false;
permutation.remove(permutation.size() - 1);
}
}
}
C++题解
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: A list of permutations.
*/
vector<vector<int> > permute(vector<int> nums) {
vector<vector<int> > res;
int n = nums.size();
if (n == 0) {
res.push_back(vector<int>());
return res;
}
helper(res, nums, n - 1);
return res;
}
void helper(vector<vector<int> > &res, vector<int> nums, int n){
if(n == 0){
res.push_back(nums);
}
for(int i = 0 ; i <= n; i++){
swap(nums[i], nums[n]);
helper(res, nums, n - 1);
swap(nums[i], nums[n]);
}
}
};
python题解
class Solution:
"""
@param nums: A list of Integers.
@return: A list of permutations.
"""
def permute(self, nums):
# write your code here
def _permute(result, temp, nums):
if nums == []:
result += [temp]
else:
for i in range(len(nums)):
_permute(result, temp + [nums[i]], nums[:i] + nums[i+1:])
if nums is None:
return []
if nums is []:
return [[]]
result = []
_permute(result, [], sorted(nums))
return result