46. Permutations
https://leetcode.com/problems/permutations/
Related problems
47-permutations-ii
78-subsets
90-subsets-ii
39-combination-sum
---
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]---
Related problems
47-permutations-ii
78-subsets
90-subsets-ii
39-combination-sum
---
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public List<List<Integer>> permute(int[] nums) { | |
List<List<Integer>> ans = new ArrayList<List<Integer>>(); | |
// faster lookup over set contains or list contains | |
boolean[] visited = new boolean[nums.length]; | |
dfs(nums, visited, new ArrayList<Integer>(), ans); | |
return ans; | |
} | |
private void dfs(int[] nums, boolean[] visited, List<Integer> prefix, List<List<Integer>> ans) { | |
if (prefix.size() == nums.length) { | |
ans.add(new ArrayList<Integer>(prefix)); | |
return; | |
} | |
for (int i = 0; i < nums.length; i++) { | |
if (visited[i]) { | |
continue; | |
} | |
prefix.add(nums[i]); | |
visited[i] = true; | |
dfs(nums, visited, prefix, ans); | |
// Backtrack | |
prefix.remove(prefix.size() - 1); | |
visited[i] = false; | |
} | |
} | |
} |