1.元素不可重复
package com.hanzheng.algorithm.backtrace;
import java.util.LinkedList;
import java.util.List;
/**
* 元素无重复,不可复选,N个元素的所有子集
*/
public class AllSubsets {
static List<List<String>> res = new LinkedList<>();
static LinkedList<String> track = new LinkedList<>();
public static void main(String[] args) {
String [] nums = new String[]{"a","b"};
res = subsets(nums);
for (List<String> e : res) {
System.out.println(e);
}
}
private static List<List<String>> subsets(String[] nums) {
backtrack(nums,0);
return res;
}
private static void backtrack(String[] nums, int start) {
// 到达一个节点就添加一个元素
// []
res.add(new LinkedList<>(track));
for (int i = start; i < nums.length; i++) {
// backtrack:[] --> [a]
// backtrack:[] --> [a] --> [b]
// backtrack:[] --> [a] --> [b] --> [c]
track.add(nums[i]);
backtrack(nums,i+1);
track.removeLast();
}
}
}
2.元素可重复
package com.hanzheng.algorithm.backtrace;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class AllSubsetsWithDuplicate {
static List<List<String>> res = new LinkedList<>();
static LinkedList<String> track = new LinkedList<>();
public static void main(String[] args) {
String[] nums = new String[]{"a", "b", "b","c"};
res = subsets(nums);
for (List<String> e : res) {
System.out.println(e);
}
}
private static List<List<String>> subsets(String[] nums) {
Arrays.sort(nums);
backtrack(nums, 0);
return res;
}
private static void backtrack(String[] nums, int start) {
res.add(new LinkedList<>(track));
for (int i = start; i < nums.length; i++) {
if (i > 0 && nums[i].equals(nums[i - 1])) {
continue;
}
track.addLast(nums[i]);
backtrack(nums, i + 1);
track.removeLast();
}
}
}