Sunday, August 21, 2016

Leetcode 78. Subsets

Answer 1:
 public class Solution {  
   public IList<IList<int>> Subsets(int[] nums) {  
     List<IList<int>> ret = new List<IList<int>>();  
     if (nums == null)  
     {  
       return ret;  
     }  
     //Array.Sort(nums);  
     List<int> cur = new List<int>();  
     helper(nums, 0, cur, ret);  
     return ret;  
   }  
   void helper(int[] nums, int step, List<int> cur, List<IList<int>> ret)  
   {  
     ret.Add(new List<int>(cur));  
     for (int i = step; i < nums.Length; i++)  
     {  
       cur.Add(nums[i]);  
       helper(nums, i+1, cur, ret);  
       cur.RemoveAt(cur.Count - 1);  
     }  
   }  
 }  
Answer 2:
 public class Solution {  
   public IList<IList<int>> Subsets(int[] nums) {  
     List<IList<int>> ret = new List<IList<int>>();  
     if (nums == null)  
     {  
       return ret;  
     }  
     List<int> start = new List<int>();  
     ret.Add(start);  
     helper(nums, ret);  
     return ret;  
   }  
   void helper(int[] nums, List<IList<int>> ret)  
   {  
     for (int i = 0; i < nums.Length; i++)  
     {  
       List<IList<int>> newResults = new List<IList<int>>();  
       foreach(var prev in ret)  
       {  
         List<int> newlist = new List<int>(prev);  
         newlist.Add(nums[i]);  
         newResults.Add(newlist);  
       }  
       ret.AddRange(newResults);  
     }  
   }  
 }  

No comments:

Post a Comment