subset 子集
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
排序两个字提前写在试卷上
for循环里面都是对nums[i]进行操作的
class Solution { public List<List<Integer>> subsets(int[] nums) { //cc List<List<Integer>> result = new ArrayList<>(); List<Integer> temp = new ArrayList<>(); if (nums == null) return null; if (nums.length == 0) return result; //排序总是可以想一想的 Arrays.sort(nums); backtrace(nums, 0, temp, result); return result; } public void backtrace(int[] nums, int start, List<Integer> temp, List<List<Integer>> result) { result.add(new ArrayList(temp)); for (int i = start; i < nums.length; i++) { temp.add(nums[i]); //这里应该是i + 1 backtrace(nums, i + 1, temp, result); temp.remove(temp.size() - 1); } } }