题目:
给定一个没有重复数字的序列, 返回其所有可能的全排列.
示例:
输入: [1,2,3]
输出:
- [
- ?[1,2,3],
- ?[1,3,2],
- ?[2,1,3],
- ?[2,3,1],
- ?[3,1,2],
- ?[3,2,1]
- ]
Java 实现:
- class Solution {
- /*
- time complexity: O(n!) space complexity : O(n)
- 时间复杂度不懂的看这: https://www.1point3acres.com/bbs/thread-117602-1-1.html
- 递归法解本题
- */
- public List<List<Integer>> permute(int[] nums) {
- List<List<Integer>> res = new ArrayList<>();
- // 边界条件判断
- if(nums == null || nums.length == 0) return res;
- helper(res, new ArrayList<>(), nums);
- return res;
- }
- // 辅助函数 res, list, nums 数组
- public static void helper(List<List<Integer>> res, List<Integer> list, int[] nums){
- //res 添加 list
- if(list.size() == nums.length){
- res.add(new ArrayList<>(list));
- return ;
- }
- for(int i = 0; i < nums.length ; i++){
- //ArrayList 的 list 中是否包含 nums 的当前元素
- if(list.contains(nums[i])) continue; //O(n)
- // 否则看看下一个是否满足要求
- list.add(nums[i]);
- helper(res, list, nums);
- list.remove(list.size() - 1);
- }
- }
- }
来源: http://www.bubuko.com/infodetail-3086786.html