【leetcode】Array——Subsets(78)
2016-02-11 22:39
429 查看
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后:[ ] [1]
输入2后:[ ] [1] [2] [1,2]
输入3后:[ ] [1] [2] [1,2] [3] [1,3] [2,3] [1,2,3]
代码:
public List<List<Integer>> subsets(int[]
nums) {
List<List<Integer>> results =
new ArrayList<>();
results.add(new ArrayList<Integer>());
if (nums.length==0)
return
results;
Arrays.sort(nums);
for(int
i:nums){
List<List<Integer>> temp =
new ArrayList<>();
for(List<Integer>
list:results){
List<Integer>a =
new ArrayList<>(list);
a.add(i);
temp.add(a);
}
results.addAll(temp);
}
return
results;
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后:[ ] [1]
输入2后:[ ] [1] [2] [1,2]
输入3后:[ ] [1] [2] [1,2] [3] [1,3] [2,3] [1,2,3]
代码:
public List<List<Integer>> subsets(int[]
nums) {
List<List<Integer>> results =
new ArrayList<>();
results.add(new ArrayList<Integer>());
if (nums.length==0)
return
results;
Arrays.sort(nums);
for(int
i:nums){
List<List<Integer>> temp =
new ArrayList<>();
for(List<Integer>
list:results){
List<Integer>a =
new ArrayList<>(list);
a.add(i);
temp.add(a);
}
results.addAll(temp);
}
return
results;
相关文章推荐
- 118. Pascal's Triangle LeetCode
- 【leetcode】Array——Trapping Rain Water(42)
- 【leetcode】Array——Triangle(120)
- 【leetcode】Array——Unique Paths II(63)
- 华为机试题:可怕的阶乘
- java常见问题
- 66. Plus One LeetCode
- Java—设计模式(工厂模式)
- K - Digital Roots(第二季水)
- slidingMenu有时候需要关闭侧边栏
- django学习之 pdf报表(表格)生成
- c语言:键盘上回车的作用相当于\n,是一个字符
- 【leetcode】Array——Unique Paths(62)
- 26. Remove Duplicates from Sorted Array LeetCode
- 【leetcode】Array——word search(79)
- 关于编程语言中的显式\隐式初始化
- PECL 和 PEAR 有什么区别?
- 27. Remove Element LeetCode
- leetcode191题 题解 翻译 C语言版 Python版
- Socket的简单认识