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],
[]
]
难度:medium
题目:给定一不含重复元素的集合,求其所有子集。
注意:答案不能包含重复的子集。
思路:递归
Runtime: 1 ms, faster than 100.00% of Java online submissions for Subsets.
Memory Usage: 37.2 MB, less than 0.96% of Java online submissions for Subsets.
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
subsets(nums, 0, i + 1, new Stack<>(), result);
}
result.add(new ArrayList<>());
return result;
}
private void subsets(int[] nums, int idx, int k, Stack<Integer> stack, List<List<Integer>> result) {
if (k <= 0) {
result.add(new ArrayList<>(stack));
return;
}
for (int i = idx; i < nums.length - k + 1; i++) {
stack.push(nums[i]);
subsets(nums, i + 1, k - 1, stack, result);
stack.pop();
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。