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]
.
Given a collection of distinct 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], [3,2,1] ]
给一个没有重复的数组,返回全部的排列可能。
解法:递归Backtracking
Java:
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
// Arrays.sort(nums); // not necessary
backtrack(list, new ArrayList<>(), nums);
return list;
}
private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums){
if(tempList.size() == nums.length){
list.add(new ArrayList<>(tempList));
} else{
for(int i = 0; i < nums.length; i++){
if(tempList.contains(nums[i])) continue; // element already exists, skip
tempList.add(nums[i]);
backtrack(list, tempList, nums);
tempList.remove(tempList.size() - 1);
}
}
}
Python: Recursion
class Solution:
# @param num, a list of integer
# @return a list of lists of integers
def permute(self, num):
result = []
used = [False] * len(num)
self.permuteRecu(result, used, [], num)
return result
def permuteRecu(self, result, used, cur, num):
if len(cur) == len(num):
result.append(cur[:])
return
for i in xrange(len(num)):
if not used[i]:
used[i] = True
cur.append(num[i])
self.permuteRecu(result, used, cur, num)
cur.pop()
used[i] = False
C++: Recursion
class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
vector<vector<int> > res;
permuteDFS(num, 0, res);
return res;
}
void permuteDFS(vector<int> &num, int start, vector<vector<int> > &res) {
if (start >= num.size()) res.push_back(num);
for (int i = start; i < num.size(); ++i) {
swap(num[start], num[i]);
permuteDFS(num, start + 1, res);
swap(num[start], num[i]);
}
}
};
C++: Recursion
class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
vector<vector<int> > res;
vector<int> out;
vector<int> visited(num.size(), 0);
permuteDFS(num, 0, visited, out, res);
return res;
}
void permuteDFS(vector<int> &num, int level, vector<int> &visited, vector<int> &out, vector<vector<int> > &res) {
if (level == num.size()) res.push_back(out);
else {
for (int i = 0; i < num.size(); ++i) {
if (visited[i] == 0) {
visited[i] = 1;
out.push_back(num[i]);
permuteDFS(num, level + 1, visited, out, res);
out.pop_back();
visited[i] = 0;
}
}
}
}
};
类似题目:
[LeetCode] 47. Permutations II 全排列 II
[LeetCode] 31. Next Permutation 下一个排列
[LeetCode] 60. Permutation Sequence 序列排序
All LeetCode Questions List 题目汇总