Saturday, June 22, 2019

78. Subsets - Backtracking topic review

78. Subsets - Here is my post on leetcode discuss I wrote on June 22, 2019.


I am reviewing backtracking pattern, here is the article written by a Google engineer. What I like to do is to post all practice first, and then figure out how to master the backtracking pattern.
Here are highlights of my practice:
  1. Start from base case, empty set with no element;
  2. Go over each sublist in the list, add the current element into the sublist.

public class Solution {
    public IList<IList<int>> Subsets(int[] nums)
        {
            if (nums == null)
                return new List<IList<int>>();

            var length = nums.Length;
            var powerSet = new List<IList<int>>(); 

            for (int i = 0; i < length; i++)
            {
                var current = nums[i];

                if (i == 0)
                {
                    var subsets = new List<int>();
                    subsets.Add(current);

                    powerSet.Add(new List<int>());
                    powerSet.Add(subsets);
                }
                else
                {
                    var count = powerSet.Count;

                    for (int j = 0; j < count; j++)
                    {
                        var list = new List<int>(powerSet[j]);
                        list.Add(current);

                        powerSet.Add(list);
                    }
                }
            }

            return powerSet;
        }
}

No comments:

Post a Comment