SubsetII
来源:互联网 发布:知画的孩子是谁的 编辑:程序博客网 时间:2024/06/15 21:05
Given a collection of integers that might contain duplicates, 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,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], []]
public class Solution { public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {// Start typing your Java solution below// DO NOT write main() functionArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();res.add(new ArrayList<Integer>());Arrays.sort(num);int start = 0;for(int i = 0; i < num.length; i++){int size = res.size();for(int j = start; j < size; j++){ArrayList<Integer> sub = new ArrayList<Integer>(res.get(j));sub.add(num[i]);res.add(sub);}if(i < num.length - 1 && num[i + 1] == num[i])start = size;elsestart = 0;}return res;}}
For [1, 2, 3], order:
[]
[1]
[2] [1, 2]
[3] [1, 3] [2, 3] [1, 2, 3]
For [1, 2, 2], order:
[]
[1]
[2] [1, 2]
(start = size) [2, 2] [1, 2, 2]
public class Solution { ArrayList<ArrayList<Integer>> ret;ArrayList<Integer> cur;public void DFS(int[] num, int n) {if (num.length == n) {ret.add(new ArrayList<Integer>(cur));return;}int count = 1;while (n + 1 < num.length && num[n] == num[n + 1]) {count++;n++;}for (int i = 0; i <= count; i++) {for (int j = 0; j < i; j++)cur.add(num[n]);DFS(num, n + 1);for (int j = 0; j < i; j++)cur.remove(cur.size() - 1);}}public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {// Start typing your Java solution below// DO NOT write main() functionret = new ArrayList<ArrayList<Integer>>();cur = new ArrayList<Integer>();Arrays.sort(num);DFS(num, 0);return ret;}}For [1, 2, 3], order: [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
- SubsetII
- subsetII leetcode c++
- LeetCode90——SubsetII
- 【leetcode-90】SubsetII(java 语言)
- vb和vb.net事件机制
- fstream
- Python type and object relationship
- 把解压缩版的tomcat6注册成服务并设置自启动
- Sublime Text 2 快捷键等TIPS
- SubsetII
- 用游标来循环处理数据( DECLARE the_cursor CURSOR )
- 数组查找
- echo
- ( ) HDU 4159 Indomie
- go - 变量和常量
- 直接把Jsp页面保存或导出Excel表格(最简单的导出Excel的方式)
- Jedis客户端使用——2
- printf() 函数压栈方式 从右到左压栈