【举一反三】: 剑指27.字符串的排列
☆☆回溯算法入门级经典题目,理论讲解及分类习题:回溯算法入门级详解 + 练习(持续更新)
思路1:标记数组
思路2:交换位置。相比思路1,空间复杂度低。
class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<>(); if (nums == null || nums.length < 1) return res; dfs(nums, 0 ,res); // 通过交换 // boolean[] visited = new boolean[nums.length]; // dfs1(nums,visited,new ArrayList<>() ,res); // 标记数组来处理填过的数 return res; } private void dfs1(int[] nums,boolean[] visited,List<Integer> list, List<List<Integer>> res) { if (list.size() == nums.length) { res.add(new ArrayList<>(list)); return; } for (int i = 0; i < nums.length; i++) { if (visited[i]) continue; visited[i] = true; list.add(nums[i]); dfs1(nums, visited, list, res); visited[i] = false; list.remove(list.size() - 1); } } private void dfs(int[] nums, int start, List<List<Integer>> res) { if (start == nums.length) { List<Integer> list = new ArrayList<>(); for (int num : nums) { list.add(num); } res.add(list); return; } for (int i = start; i < nums.length; i++) { swap(nums, start, i); // 每交换一次就确定一个位置上的元素 dfs(nums, start + 1, res); swap(nums, start, i); } } private void swap(int[] nums, int a, int b) { int temp = nums[a]; nums[a] = nums[b]; nums[b] = temp; } }