title: leetcode-46-全排列(java)
date: 2019-09-11 19:26:29
categories:
- leetcode
tags: - leetcode
全排列(java)
-
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 -
解法:回溯,每次交换后再交换,直到最后,又恢复原来位置
class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> list = new ArrayList<>(); doPermutation(list,nums,0); return list; } public void swap(int[] nums,int a,int b){ int temp = nums[a]; nums[a] = nums[b]; nums[b] = temp; } public void doPermutation(List<List<Integer>> list,int[] nums,int start){ if(start==nums.length-1){ list.add(Arrays.stream(nums).boxed().collect(Collectors.toList())); }else{ for (int i=start;i<nums.length;i++){ swap(nums,i,start); doPermutation(list,nums,start+1); swap(nums,i,start); } } } }
-
回溯法改进:友情提醒,后面几天刷的题都要注意是否可以用回溯
class Solution { public List<List<Integer>> permute(int[] nums) { if (nums == null || nums.length == 0) return Collections.emptyList(); List<List<Integer>> res = new LinkedList<>(); List<Integer> list = new LinkedList<>(); boolean[] visited = new boolean[nums.length]; helper(nums, res, list, visited); return res; } public void helper(int[] nums, List<List<Integer>> res, List<Integer> list, boolean[] visited) { if (list.size() == nums.length) { res.add(new LinkedList(list)); return; } for (int i = 0; i < nums.length; i++) { if (visited[i]) continue; visited[i] = true; list.add(nums[i]); helper(nums, res, list, visited); list.remove(list.size() - 1); visited[i] = false; } } }