1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { public List<List<Integer>> permute(int[] nums) { int length = nums.length; List<List<Integer>> res = new ArrayList<>(); if (length == 0) { return res; } List<Integer> tmp_list = new ArrayList<>(); boolean[] used = new boolean[length]; bfs(0, nums, used, tmp_list, res, length); return res; } public void dfs(int depth, int[] nums, boolean[] used, List<Integer> list, List<List<Integer>> res, int length) { if (depth == length) { res.add(new ArrayList<Integer>(list)); return; } for (int i = 0; i < length; i++) { if(used[i] == false) { used[i] = true; list.add(nums[i]); bfs(depth + 1, nums, used, list, res, length); list.remove(list.size() - 1); used[i] = false; } } } }
|