《LeetCode力扣练习》代码随想录——回溯算法(全排列—Java)
刷题思路来源于 代码随想录
46. 全排列
-
回溯
class Solution { private List<Integer> path = new ArrayList<>(); private List<List<Integer>> result = new ArrayList<>(); private boolean[] used; public List<List<Integer>> permute(int[] nums) { used = new boolean[nums.length]; backtrack(nums); return result; } private void backtrack(int[] nums) { if (path.size() == nums.length) { result.add(new ArrayList<>(path)); return; } for (int i = 0; i < nums.length; i++) { if (used[i] == true) { continue; } used[i] = true; path.add(nums[i]); backtrack(nums); used[i] = false; path.remove(path.size() - 1); } return; } }