广度优先遍历(bfs)和深度优先遍历(dfs)
深度优先遍历找子集
package org.example.algorithm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SubSet {
public static void main(String[] args) {
int[] nums = {1,2};
List<List<Integer>> result = new SubSet().subset(nums);
for (List<Integer> list:result){
for(Integer i:list){
System.out.println(i + "");
}
System.out.println();
}
}
public List<List<Integer>> subset(int[] nums){
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (nums == null || nums.length == 0){
result.add(new ArrayList<Integer>());
return result;
}
Arrays.parallelSort(nums);
List<Integer> list = new ArrayList<>();
dfs(nums,result,list,0);
return result;
}
public void dfs(int[] nums,List<List<Integer>> result,List<Integer> list,int pos){
result.add(new ArrayList<Integer>(list));
for(int i = pos; i < nums.length; i++){
list.add(nums[i]);
dfs(nums,result,list,i+1);
list.remove(list.size() - 1);
}
}
}
求子集的第二种暴力解法
package org.example.algorithm;
public class SubSet2 {
public static void main(String[] args) {
subSet("abc");
}
public static void subSet(Object obj){
String s = String.valueOf(obj);
for(int i = 0; i < s.length(); i++){
for(int j = i + 1; j <= s.length(); j++){
System.out.println(s.substring(i,j));
}
}
}
}