Subset
Title description: Give you an integer array nums, the elements in the array are different from each other. Return all possible subsets (power sets) of the array.
The solution set cannot contain duplicate subsets. You can return the solution set in any order.
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/subsets/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution 1: dfs (depth first traversal)
Declare two global variables as the result set (result) and the current path (path), and add a depth-first traversal method. The specific logic of the method is as follows:
- When
k=0
, that is, there are already k numbers in the current path, it means that the current path meets the conditions and is added to the result set;- Then traverse the numbers starting from 1, recursively call the dfs method, and remove the last number of the current path from the path after the call.
The above process is LeetCode-077-combination . The difference is that this question needs to traverse all possible combinations of the number of elements (between 0 and n), and then add them to the result set.
import java.util.ArrayList;
import java.util.List;
public class LeetCode_078 {
/**
* 结果集
*/
private static List<List<Integer>> result = new ArrayList<>();
/**
* 当前路径
*/
private static List<Integer> path = new ArrayList<>();
/**
* 多重调用dfs(深度优先遍历)
*
* @param nums
* @return
*/
public static List<List<Integer>> subsets(int[] nums) {
result.add(new ArrayList<>());
for (int i = 1; i <= nums.length; i++) {
path = new ArrayList<>();
dfs(0, nums, i);
}
return result;
}
/**
* 深度优先遍历
*
* @param index 路径的起始位置
* @param nums 原始的数组
* @param k 路径剩下还需要几个值
*/
private static void dfs(int index, int[] nums, int k) {
if (k == 0) {
/**
* 当前已经有k个值,加到结果集中
*/
result.add(new ArrayList<>(path));
return;
}
for (int i = index; i < nums.length; i++) {
path.add(nums[i]);
dfs(i + 1, nums, k - 1);
/**
* 将当前路径的最后一个值去掉,然后继续遍历
*/
path.remove(path.size() - 1);
}
}
public static void main(String[] args) {
int[] nums = new int[]{1, 2, 3};
for (List<Integer> integers : subsets(nums)) {
for (Integer integer : integers) {
System.out.print(integer + " ");
}
System.out.println();
}
}
}
[Daily Message] “Sit, it’s better to start”. When there is no achievement, learn to do it, accumulate strength and wait for the opportunity.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。