Created
May 8, 2022 02:13
-
-
Save svaza/49536682c877598adec4f5e1806d7fff to your computer and use it in GitHub Desktop.
Permutations
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
using System.Collections.Generic; | |
public class Solution { | |
public IList<IList<int>> Permute(int[] nums) { | |
IList<IList<int>> solution = new List<IList<int>>(); | |
Traverse(nums, new HashSet<int>(), new List<int>(), solution); | |
return solution; | |
} | |
private void Traverse(int[] nums, HashSet<int> currentSet, List<int> currentList, IList<IList<int>> solution) | |
{ | |
if(currentSet.Count == nums.Length) | |
{ | |
solution.Add(new List<int>(currentList)); | |
return; | |
} | |
foreach(var num in nums) | |
{ | |
if(currentSet.Add(num)) | |
{ | |
currentList.Add(num); | |
Traverse(nums, currentSet, currentList, solution); | |
if(currentSet.Count > 0) | |
{ | |
currentSet.Remove(num); | |
currentList.RemoveAt(currentList.Count - 1); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment