题目链接:https://leetcode.com/problems/subsets/
题目:
Given a set of distinct integers, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
解题思路:
1、先把每一个数组元素都放到 subList 中,把 subList 加入到 List 中
2、遍历上一轮中加入到 List 中的那些 subList ,依次判断每个 subList 是否包含数组中的每一个元素,若不包含,就将其与 subList 中的元素合并为一个新的 subList。判断 List 是否包含该 subList,若不包含,则把该 subList 加入到 List 中。依次类推。当最新一轮创建的 subList 只有一个时,停止循环。
3、创建一个空 subList 加入到 List 中。
数组 [1, 2, 3]
第一轮 List [[1],[2],[3]]
第二轮 List [[1],[2],[3], [1,2],[1,3],[2,3]]
(上一轮的subList) (新一轮产生的subList)
例如:上一轮的[1]包含数组元素1,跳过此次循环;上一轮的[1]不包含数组元素2,创建新的 subList,将上一轮的 subList [1]添加到新的 subList, 再将元素2添加到新的 subList,得到[1,2]。最后检查 List 中是否有[1,2]这个元素,若没有则添加。
第三轮 List [[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]
(上 一 轮)(新一轮)
第四轮 List [[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3],[]]
注意:
判断 List 中是否包含 subList 时,需要将 subList 先进行排序(Collections.sort(subList, comparator))。
原因:List.contains(subList); 元素个数,大小,顺序完全一致的两个 subList 才是相同。即,若List中已有[1, 2],但 List.contains(subList); 认为没有包含[2, 1]。
public class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> list = new ArrayList();
int len = nums.length;
for(int j = 0; j < len; j ++) {
List<Integer> subList = new ArrayList();
subList.add(nums[j]);
list.add(subList);
}
int start = 0;
int end = list.size() - 1;
while(end != start) {
int n = 0;
while(start <= end) {
for(int j = 0; j < len; j ++) {
if(list.get(start).contains(nums[j]))
continue;
List<Integer> subList = new ArrayList();
subList.addAll(list.get(start));
subList.add(nums[j]);
Collections.sort(subList, new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
return a.compareTo(b);
}
});
if(list.contains(subList))
continue;
else {
list.add(subList);
n ++;
}
}
start ++;
}
start = end + 1;
end = end + n;
}
list.add(new ArrayList<Integer>());
return list;
}
}
10 / 10 test cases passed.
Status: Accepted
Runtime: 460 ms
p.s. 效率偏低,算法有待优化!
大神思路参考:http://blog.youkuaiyun.com/linhuanmars/article/details/24286377