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], [] ]
1 public class Solution { 2 List<List<Integer>> ans = new ArrayList<>(); 3 public List<List<Integer>> subsets(int[] nums) { 4 List<Integer> list = new ArrayList<>(); 5 ans.add(list); 6 for(int i = 0; i < nums.length; i++){//按照 取subset的长度 一个个遍历一遍 7 findSubset(list,nums,i+1,0); 8 } 9 return ans; 10 } 11 12 public void findSubset(List<Integer> list, int[] nums, int k, int s){ 13 if(k == 0){ 14 List<Integer> tmp = new ArrayList<>(list); 15 ans.add(tmp); 16 return; 17 } 18 for(int i = s; i < nums.length; i++){ 19 list.add(nums[i]); 20 findSubset(list,nums,k-1,i+1); 21 list.remove(list.size()-1); 22 } 23 } 24 }
一个小的总结帖,二刷再试下其他解法。
https://discuss.leetcode.com/topic/46159/a-general-approach-to-backtracking-questions-in-java-subsets-permutations-combination-sum-palindrome-partitioning