C# recursive solution


  • 0
    M
    public IList<IList<int>> PermuteUnique(int[] nums) {
        var map = new Dictionary<int,int>();
        foreach(int num in nums)
        {
            if(map.ContainsKey(num))
                map[num]++;
            else
                map.Add(num,1);
        }
        
        return Helper(map);
    }
    
    IList<IList<int>> Helper(IDictionary<int,int> map)
    {
        var result = new List<IList<int>>();
        
        foreach(var pair in map.ToArray())
        {
            int num = pair.Key;
            int count = pair.Value;
            
            if(count == 0)
                continue;
                
            map[num]--;
            var before = Helper(map);
            map[num]++;
            
            foreach(var inner in before)
                inner.Add(num);
                
            result.AddRange(before);
        }
        
        if(result.Count == 0)
            result.Add(new List<int>());
            
        return result;
    }

Log in to reply
 

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