【LeetCode】 46. Permutations 全排列(Medium)(JAVA)
题目地址: https://leetcode.com/problems/permutations/
题目描述:
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
题目大意
给定一个没有重复数字的序列,返回其所有可能的全排列。
解题方法
通过递归,得到序列
要点:
1、对从 list 删除的元素,重新添加;加入 cur 的元素,重新删除
2、cur 加入到 res 中,必须 new ArrayList<>(),不然加入的只是指针
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> cur = new ArrayList<>();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
list.add(nums[i]);
}
pH(res, cur, list);
return res;
}
public void pH(List<List<Integer>> res, List<Integer> cur, List<Integer> list) {
if (list.size() == 0) {
res.add(new ArrayList<Integer>(cur));
return;
}
for (int i = 0; i < list.size(); i++) {
int temp = list.remove(i);
cur.add(temp);
pH(res, cur, list);
cur.remove(cur.size() - 1);
list.add(i, temp);
}
}
}
执行用时 : 3 ms, 在所有 Java 提交中击败了 33.10% 的用户
内存消耗 : 41.3 MB, 在所有 Java 提交中击败了 5.03% 的用户