LeetCode: Subsets 解题报告

Subsets

Given a set of distinct integers, S, 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 S = [1,2,3], a solution is:

[

[3],

[1],

[2],

[1,2,3],

[1,3],

[2,3],

[1,2],

[]

]

SOLUTION 1:

使用九章算法的模板:

递归解决。

1. 先对数组进行排序。

2. 在set中依次取一个数字出来即可,因为我们保持升序,所以不需要取当前Index之前的数字。

 1 public class Solution {
 2     public List<List<Integer>> subsets(int[] S) {
 3         List<List<Integer>> ret = new ArrayList<List<Integer>>();
 4         if (S == null) {
 5             return ret;
 6         }
 7
 8         Arrays.sort(S);
 9
10         dfs(S, 0, new ArrayList<Integer> (), ret);
11
12         return ret;
13     }
14
15     public void dfs(int[] S, int index, List<Integer> path, List<List<Integer>> ret) {
16         ret.add(new ArrayList<Integer>(path));
17
18         for (int i = index; i < S.length; i++) {
19             path.add(S[i]);
20             dfs(S, i + 1, path, ret);
21             path.remove(path.size() - 1);
22         }
23     }
24 }

SOLUTION 2:

相当牛逼的bit解法。基本的想法是,用bit位来表示这一位的number要不要取,第一位有1,0即取和不取2种可能性。所以只要把0到N种可能

都用bit位表示,再把它转化为数字集合,就可以了。

Ref: http://www.fusu.us/2013/07/the-subsets-problem.html

There are many variations of this problem, I will stay on the general problem of finding all subsets of a set. For example if our set is [1, 2, 3] - we would have 8 (2 to the power of 3) subsets: {[], [1], [2], [3], [1, 2], [1, 3], [1, 2, 3], [2, 3]}. So basically our algorithm can‘t be faster than O(2^n) since we need to go through all possible combinations.

There‘s a few ways of doing this. I‘ll mention two ways here - the recursive way, that we‘ve been taught in high schools; and using a bit string.

Using a bit string involves some bit manipulation but the final code can be found easy to understand. The idea  is that all the numbers from 0 to 2^n are represented by unique bit strings of n bit width that can be translated into a subset. So for example in the above mentioned array we would have 8 numbers from 0 to 7 inclusive that would have a bit representation that is translated using the bit index as the index of the array.


Nr


Bits


Combination


0


000


{}


1


001


{1}


2


010


{2}


3


011


{1, 2}


4


100


{3}


5


101


{1, 3}


6


110


{2, 3}


7


111


{1, 2, 3}

 1 public class Solution {
 2     public List<List<Integer>> subsets(int[] S) {
 3         List<List<Integer>> ret = new ArrayList<List<Integer>>();
 4         if (S == null || S.length == 0) {
 5             return ret;
 6         }
 7
 8         int len = S.length;
 9         Arrays.sort(S);
10
11         // forget to add (long).
12         long numOfSet = (long)Math.pow(2, len);
13
14         for (int i = 0; i < numOfSet; i++) {
15             // bug 3: should use tmp - i.
16             long tmp = i;
17
18             ArrayList<Integer> list = new ArrayList<Integer>();
19             while (tmp != 0) {
20                 // bug 2: use error NumberOfTrailingZeros.
21                 int indexOfLast1 = Long.numberOfTrailingZeros(tmp);
22                 list.add(S[indexOfLast1]);
23
24                 // clear the bit.
25                 tmp ^= (1 << indexOfLast1);
26             }
27
28             ret.add(list);
29         }
30
31         return ret;
32     }
33
34 }

GITHUB: https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/dfs/Subsets.java

时间: 2024-08-03 15:21:01

LeetCode: Subsets 解题报告的相关文章

LeetCode: Permutations 解题报告

Permutations Given a collection of numbers, return all possible permutations. For example,[1,2,3] have the following permutations:[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. SOLUTION 1: 经典的递归回溯题目,一次ACCEPT. 请也参考上一个题目LeetCode: Combination

[LeetCode]3Sum,解题报告

题目 Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The so

[LeetCode]Candy, 解题报告

前言 回学校写论文差不多快二周的时间了,总结一句话,在学校真舒服.花了7天时间搞定了毕业论文初稿(之所以这么快肯定跟我这三年的工作量相关了),不过今天导师批复第二章还是需要修改.此外,最近迷上打羽毛球,确实很爽,运动量仅此于篮球,可以场地有限,哎,且打且珍惜吧. 题目 There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these chi

【LeetCode】Subsets 解题报告

[题目] Given a set of distinct integers, S, 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 S = [1,2,3], a solution is: [ [3], [1], [2], [1,2,

Single Number | LeetCode OJ 解题报告

题目网址:https://oj.leetcode.com/problems/single-number/ 题目描述: Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without usin

Add Two Numbers | LeetCode OJ 解题报告

题目网址:https://oj.leetcode.com/problems/add-two-numbers/ 题目描述: You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return i

Two Sum | LeetCode OJ 解题报告

题目网址:https://oj.leetcode.com/problems/two-sum/ 题目描述: Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, whe

LeetCode: isSameTree1 解题报告

isSameTree1 Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. SOLUTION 1 & SOLUTION 2: 以下是递归及非递归解法: 1. 递归解法就是判断当前节点是

LeetCode: solveSudoku 解题报告

Sudoku SolverWrite a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. SOLUTION: ref: http://blog.csdn.net/fightforyourdream/articl