Based on the combinations problem, we use a for loop to call the method created in that problem and this problem will be solved. Later we‘ll add bit manipulation.
Code:
public class Solution { public List<List<Integer>> subsets(int[] nums) { Arrays.sort(nums); List<List<Integer>> resultList = new ArrayList<>(); int len = nums.length; for(int i = 0; i < len; i++){ List<Integer> list = new ArrayList<>(); addSubset(nums, len-1, 0, i+1, resultList, list); } List<Integer> list = new ArrayList<>(); resultList.add(list); return resultList; } public void addSubset(int[] nums, int n, int cur, int k, List<List<Integer>> result, List<Integer> list){ if(k == 0){ result.add(new ArrayList<>(list)); return; } list.add(nums[cur]); addSubset(nums, n, cur+1, k-1, result, list); list.remove(list.size()-1); if(cur == n-k+1) return; addSubset(nums, n, cur+1, k, result, list); } }
时间: 2024-10-13 10:50:30