题目:
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], [] ]
链接:https://leetcode.com/problems/subsets/#/description
4/22/2017
算法班
提到了递归的三要素?
1 public class Solution { 2 public List<List<Integer>> subsets(int[] nums) { 3 List<List<Integer>> ret = new ArrayList<>(); 4 5 if (nums == null) { 6 return ret; 7 } 8 9 Arrays.sort(nums); 10 11 helper(ret, new ArrayList<Integer>(), nums, 0); 12 13 return ret; 14 } 15 16 private void helper(List<List<Integer>> ret, 17 ArrayList<Integer> subset, 18 int[] nums, 19 int startIndex) { 20 // return condition is implicit here, since subset ends when reach to last element of nums 21 ret.add(new ArrayList<Integer>(subset)); 22 for (int i = startIndex; i < nums.length; i++) { 23 subset.add(nums[i]); 24 helper(ret, subset, nums, i + 1); 25 subset.remove(subset.size() - 1); 26 } 27 } 28 }
有人的总结:
python大哥的几种方法,包括reduce(), itertools.combinations()https://discuss.leetcode.com/topic/15819/short-and-clear-solutions
有iterative方法的,但是不如普通方法个人感觉
更多讨论: