码迷,mamicode.com
首页 > 其他好文 > 详细

CC150 8.3

时间:2014-12-01 10:16:15      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:interview

8.3 Write a method that returns all subsets of a set.

powerSet(i) = 
  [powerSet(i - 1)] * ITEMi + // Add new item into each existing set
  [pwerSet(i - 1)] + // Existing set
  ITEMi // single new item.
powerSet(1) = ITEM1.

<T> Set<Set<T>> powerSet(Set<T> set)
{
  if (set == null || set.isEmpty())
    return Collections.emptyList();
    
  Set<Set<T>> toReturn = Sets.new();
  
  T t = set.removeFirstElement();
  Set<Set<T>> smallResults = powerSet(set);
  toReturn.addAll(smallResults);
  
  for (Set<T> s : smallResults)
  {
    Set<T> withI = Sets.copy(s).add(t);
    toReturn.add(withI);
  }
  
  toReturn.add(Sets.of(t));
  
  // Add empty one in outer method.
  // if needed.
  toReturn.add(Sets.empty());
    
  return toReturn;
}


CC150 8.3

标签:interview

原文地址:http://7371901.blog.51cto.com/7361901/1584897

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!