Leetcode 之 Subsets
2015-08-13 23:20
387 查看
Given a set of distinct integers, nums, return all possible subsets.
Note:
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数组长度相同终止循环。
10 / 10 test cases passed.
Status: Accepted
Runtime: 316 ms
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
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解