首页 > 代码库 > LeetCode Subsets
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,3], [1,3], [2,3], [1,2], []]
思路是,每次添加一个元素,就是在上一次的基础上,对每个列表加入元素,再与上一次的合并。
1 public class Solution { 2 public List<List<Integer>> subsets(int[] S) { 3 List<List<Integer>> lastList=new ArrayList<>(); 4 List<Integer> nonSet= new ArrayList<>(); 5 lastList.add(nonSet); 6 if (S==null || S.length==0) { 7 return lastList; 8 } 9 Arrays.sort(S);10 11 for (int i = 0; i < S.length; i++) {12 List<List<Integer>> tempList=new ArrayList<>(); 13 for (List<Integer> list : lastList) {14 List<Integer> currlist=new ArrayList<>();15 currlist.addAll(list);16 currlist.add(S[i]);17 tempList.add(currlist);18 }19 lastList.addAll(tempList);20 }21 return lastList;22 }23 }
LeetCode Subsets
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。