Skip to content

Instantly share code, notes, and snippets.

@svaza
Created May 8, 2022 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svaza/49536682c877598adec4f5e1806d7fff to your computer and use it in GitHub Desktop.
Save svaza/49536682c877598adec4f5e1806d7fff to your computer and use it in GitHub Desktop.
Permutations
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