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:
- Start from base case, empty set with no element;
- 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