Last active
October 4, 2018 23:40
-
-
Save hsaputra/c1a1079bf38a0871f756d457bd3144cb to your computer and use it in GitHub Desktop.
Permutations (no entry duplicate ) - https://leetcode.com/problems/permutations/description/
This file contains hidden or 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>> results = new ArrayList<List<Integer>>(); | |
if (nums == null || nums.length == 0) { | |
return results; | |
} | |
List<Integer> prefix = new ArrayList<Integer>(); | |
permutateRecursive(nums, prefix, results); | |
return results; | |
} | |
private void permutateRecursive(int[] nums, List<Integer> prefix, List<List<Integer>> results) { | |
// Stopping condition | |
if (prefix.size() == nums.length) { | |
results.add(new ArrayList<Integer>(prefix)); | |
return; | |
} | |
// Start moving elements | |
for (int i = 0; i < nums.length; i++) { | |
if (prefix.contains(nums[i])) | |
continue; | |
prefix.add(nums[i]); | |
permutateRecursive(nums, prefix, results); | |
// Dont forget to remove within same level of prefix. | |
prefix.remove(prefix.size() - 1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment