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位数,2位数。。。
[] || [1], [2], [3] || [1,2], [1,3], [2,3] || [1,2,3]
[1,2]和[1,3] 是由1生成的,[2,3]是由2生成的
所以每次只要设置两个下标,分别记录当前所在的区段(1位数还是2位数还是3位数。。即可)
每次在这个区段循环,找每个元素的最后一位,给最后一位添加比他大的数字,加到最终的list列表中,count指针加1。每轮循环结束都把start和end后移。一直到list列表最后一个元素的大小与nums数组长度相同终止循环。
List<List<Integer>> list = new ArrayList<List<Integer>>();
public List<List<Integer>> subsets(int[] nums) {
ArrayList<Integer> l = new ArrayList<Integer>();
Arrays.sort(nums);
list.add(new ArrayList<Integer>());
for(int i = 0;i < nums.length;i++){
ArrayList<Integer> tempList = new ArrayList<Integer>();
tempList.add(nums[i]);
list.add(tempList);
}
add(1,list.size() - 1,nums);
return list;
}
public void add(int start,int end,int[] nums){
while(list.get(list.size() - 1).size() < nums.length){
int count = 0;
for(int i = start; i <= end;i++){
ArrayList<Integer> lastList = (ArrayList<Integer>) list.get(i);
int lastVal = lastList.get(lastList.size() - 1);
for(int j = 0;j < nums.length;j++){
if(nums[j] > lastVal){
ArrayList<Integer> newList = new ArrayList<Integer>(lastList);
newList.add(nums[j]);
list.add(newList);
count++;
}
}
}
start = end + 1;
end += count;
}
}
10 / 10 test cases passed.
Status: Accepted
Runtime: 316 ms