public class Solution {
public IList<IList<int>> SubsetsWithDup(int[] nums) {
List<IList<int>> ret = new List<IList<int>>();
if (nums == null)
{
return ret;
}
// Have to sort first.
Array.Sort(nums);
// Create an empty result and add to ret.
List<int> start = new List<int>();
ret.Add(start);
// Resursive backtrack.
helper(nums, 0, start, ret);
return ret;
}
void helper(int[] nums, int step, List<int> current, List<IList<int>> ret)
{
for(int i = step; i < nums.Length; i++)
{
// Remove dup. The same case has been accounted for in a previous iteration.
if (i > step && nums[i] == nums[i-1])
{
continue;
}
current.Add(nums[i]);
ret.Add(new List<int>(current));
helper(nums, i + 1, current, ret);
current.RemoveAt(current.Count - 1);
}
}
}
Sunday, August 21, 2016
Leetcode 90 Subsets II
Answer:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment