C# solution: DFS and visited array


  • 0
    B
    public class Solution 
    {
        public IList<IList<int>> Permute(int[] nums) 
        {
            var result = new List<IList<int>>();
            var isVisited = new bool[nums.Length];
    
            DFS(nums, isVisited, new List<int>(), result);
    
            return result;
        }
    
        private void DFS(int[] nums, bool[] isVisited, IList<int> oneResult, IList<IList<int>> result)
        {
            if (oneResult.Count == nums.Length)
            {
                result.Add(new List<int>(oneResult));
                return;
            }
    
            for (int i = 0; i < nums.Length; i++)
            {
                if (isVisited[i]) continue;
    
                isVisited[i] = true;
                oneResult.Add(nums[i]);
                DFS(nums, isVisited, oneResult, result);
                oneResult.RemoveAt(oneResult.Count - 1);
                isVisited[i] = false;
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.