题目要求
Given a set of distinct integers, nums, return all possible subsets.Note: 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], []]
类似的题目有:
leetcode60 Permutation Sequence 可以参考leetcode77 Combinations 可以参考思路一:递归
还是利用递归的方式,在前一种情况的基础上遍历下一轮的组合情况。
public List
> subsets(int[] nums) { List
> result = new ArrayList
>(); result.add(new ArrayList ()); subsets(result, nums, 0, new ArrayList ()); return result; } public void subsets(List
> result, int[] nums, int startIndex, List currentList){ if(startIndex == nums.length){ return; } while(startIndex (currentList)); subsets(result, nums, startIndex, currentList); currentList.remove(currentList.size()-1); } }
思路2:排序后循环
起始subset集为:[]
添加S0后为:[], [S0]添加S1后为:[], [S0], [S1], [S0, S1]添加S2后为:[], [S0], [S1], [S0, S1], [S2], [S0, S2], [S1, S2], [S0, S1, S2]public List
> subsets(int[] S) { List
> res = new ArrayList<>(); res.add(new ArrayList ()); for(int i : S) { List
> tmp = new ArrayList<>(); for(List sub : res) { List a = new ArrayList<>(sub); a.add(i); tmp.add(a); } res.addAll(tmp); } return res;}
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~