Sharing C# DFS solution


  • 0
    Y

    //DFS

    public class Solution {
        public IList<IList<int>> SubsetsWithDup(int[] nums) {
            
            Array.Sort(nums);
            var result=new List<IList<int>>();
            DFS(result,nums,-1,new List<int>());
            return result;
        }
        
        
        public void DFS(IList<IList<int>> result,int[] nums, int index, IList<int> path)
        {
            result.Add(path);
            if(index==nums.Length-1)
                return;
            for(int i = index + 1;i<nums.Length;i++)
            {
                var newList=new List<int>();
                newList.AddRange(path);
                newList.Add(nums[i]);
                DFS(result, nums, i, newList);
                while(i<nums.Length-1&&nums[i]==nums[i+1])
                {
                    i+=1;
                }
            }
        }
    }

Log in to reply
 

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