0.题目
1.飞哥的题解
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<Integer> numList = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
numList.add(nums[i]);
}
List<List<Integer>> resultList = new ArrayList<>();
List<Integer> rightList = new ArrayList<>();
find(resultList, rightList, numList);
return resultList;
}
private void find(List<List<Integer>> resultList, List<Integer> rightList, List<Integer> numList) {
for (int i = 0; i < numList.size(); i++) {
Integer number = numList.remove(i);
rightList.add(number);
if (numList.isEmpty()) {
resultList.add(new ArrayList<>(rightList));
numList.add(number);
rightList.remove(rightList.size()-1);
return;
}
find(resultList, rightList, numList);
numList.add(i,number);
rightList.remove(rightList.size()-1);
}
}
}
2.官方题解
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> output = new ArrayList<Integer>();
for (int num : nums) {
output.add(num);
}
int n = nums.length;
backtrack(n, output, res, 0);
return res;
}
public void backtrack(int n, List<Integer> output, List<List<Integer>> res, int first) {
// 所有数都填完了
if (first == n) {
res.add(new ArrayList<Integer>(output));
}
for (int i = first; i < n; i++) {
// 动态维护数组
Collections.swap(output, first, i);
// 继续递归填下一个数
backtrack(n, output, res, first + 1);
// 撤销操作
Collections.swap(output, first, i);
}
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/permutations/solution/quan-pai-lie-by-leetcode-solution-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public:
void backtrack(vector<vector<int>>& res, vector<int>& output, int first, int len){
// 所有数都填完了
if (first == len) {
res.emplace_back(output);
return;
}
for (int i = first; i < len; ++i) {
// 动态维护数组
swap(output[i], output[first]);
// 继续递归填下一个数
backtrack(res, output, first + 1, len);
// 撤销操作
swap(output[i], output[first]);
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int> > res;
backtrack(res, nums, 0, (int)nums.size());
return res;
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/permutations/solution/quan-pai-lie-by-leetcode-solution-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
来源:oschina
链接:https://my.oschina.net/hengbao666/blog/4604791