您的位置:首页 > 其它

【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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: