Not a member of GistPad yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public List<List<Integer>> permute(int[] nums) {
- List<List<Integer>> result = new ArrayList<>();
- List<Integer> temp = new ArrayList<>();
- // to keep track if element is included in permutation or not
- boolean[] visited = new boolean[nums.length];
- findPermutations(nums, visited, result, temp);
- return result;
- }
- public void findPermutations(int[] nums, boolean[] visited, List<List<Integer>> result, List<Integer> temp)
- {
- // Base condition : when temp array becomes equal to actual size of array
- if(temp.size() == nums.length)
- {
- result.add(new ArrayList<>(temp));
- return;
- }
- for(int i=0; i<nums.length; i++)
- {
- if(visited[i] == false)
- {
- // solve: pick the current element if it's not added in permutation
- temp.add(nums[i]);
- visited[i] = true;
- // explore: calling recursively
- findPermutations(nums, visited, result, temp);
- // backtrack: do not pick the element
- temp.remove(temp.size() - 1);
- visited[i] = false;
- }
- }
- return;
- }
- }
RAW Paste Data
Copied
