Created
February 3, 2020 04:14
-
-
Save andriybuday/c69efb2299e2c2d6ac59c5fbeeb9c212 to your computer and use it in GitHub Desktop.
Backtracking
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
public List<List<Integer>> permute(int[] nums) { | |
List<List<Integer>> ans = new ArrayList<>(); | |
backtrack(ans, new ArrayList<Integer>(), nums); | |
return ans; | |
} | |
private void backtrack(List<List<Integer>> ans, List<Integer> ongoing, int[] nums) { | |
if(ongoing.size() == nums.length) { | |
ans.add(new ArrayList<>(ongoing)); | |
} else { | |
for(int i = 0; i < nums.length; i++) { | |
if(!ongoing.contains(nums[i])) { | |
ongoing.add(nums[i]); | |
backtrack(ans, ongoing, nums); | |
ongoing.remove(ongoing.size() - 1); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment