leetcode 78. Subsets
2016-06-24 12:36
393 查看
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums =
is:
这道题刚看到,想到了如何用数学的方法来计算有多少个解。对于每个元素都有取或者不取两种状态,那么n个元素就需要n步骤所有公式为2^n。
接下来开始程序思考,其实这个题就转换为了DFS了。 一个节点有两个节点,一个是选择,一个是不选择,走到头,就得到了结果。
代码如下
运行通过了,但是只打败了17%的人。就在想有啥更好的方法嘛,看了一下tags,发现bitmap。所以就采用bitmap的方法了。1表示选择,0表示不选择。
这回提升到了50%多了。 不知道大神们如何达到90%以上的,好想知道。
Note: 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], []]
这道题刚看到,想到了如何用数学的方法来计算有多少个解。对于每个元素都有取或者不取两种状态,那么n个元素就需要n步骤所有公式为2^n。
接下来开始程序思考,其实这个题就转换为了DFS了。 一个节点有两个节点,一个是选择,一个是不选择,走到头,就得到了结果。
代码如下
public class Solution { Stack<Integer> stack = new Stack(); List<List<Integer>> list= new ArrayList<List<Integer>>(); private void findSubset(Stack<Integer> stack, int[] nums, int offset){ if(nums.length == offset){ List<Integer> oneList = new ArrayList<Integer>(); for(Integer num : stack){ oneList.add(num); } list.add(oneList); return; } findSubset(stack, nums, offset+1); stack.push(nums[offset]); findSubset(stack, nums, offset+1); stack.pop(); } public List<List<Integer>> subsets(int[] nums) { findSubset(stack, nums, 0); return list; } }
运行通过了,但是只打败了17%的人。就在想有啥更好的方法嘛,看了一下tags,发现bitmap。所以就采用bitmap的方法了。1表示选择,0表示不选择。
public class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> list2= new ArrayList<List<Integer>>(); int n = 1; for(int i =0 ; i< nums.length; i++){ n=n*2; } for(int i = 0 ; i< n ; i ++){ List<Integer> oneList = new ArrayList<Integer>(); for(int j=0 ; j< nums.length ; j++){ if(((i>>j)&1) >0) oneList.add(nums[j]); } list2.add(oneList); } return list2; } }
这回提升到了50%多了。 不知道大神们如何达到90%以上的,好想知道。
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [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
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- 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 题解