Preface LeetCode has many string combination questions. I have previously written a binary method to solve this type of problem. Original article: string combination algorithm
Here, we will introduce a method to solve the problem of string combination using dfs.
A typical concept is dfs. Where is the starting point for adding an int pos record subset? When the loop ends, the previous layer needs to delete the newly added element.
Take the set [1, 2, 3] as an example:
Pos =-1, []
Pos = 0, [1]
Pos = 1, [1, 2]
Pos = 2, [1, 2, 3]
Pos = 2, delete 3
Pos = 1, delete 2
Pos = 2, [1, 3]
Pos = 1, delete 3
Pos = 0, delete 1
Pos = 1, [2]
Pos = 2, [2, 3]
Pos = 1, delete 3
Pos = 0, delete 2
Pos = 3, [3]
Question Given a set of distinct integers, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1, 2, 3], a solution is:
[
[3],
[1],
[2],
[1, 2, 3],
[1, 3],
[2, 3],
[1, 2],
[]
]
AC code
import java.util.ArrayList;import java.util.Arrays;public class SubSets { public static ArrayList> subsetsWithDup(int[] num) { ArrayList> res = new ArrayList>(); ArrayList
tmp = new ArrayList
(); Arrays.sort(num); res.add(tmp); dfs(0, num, tmp, res); return res; } public static void dfs(int pos, int[] num, ArrayList
tmp, ArrayList> res) { if (pos >= num.length) { return; } else { for (int i = pos; i < num.length; i++) { tmp.add(num[i]); res.add(new ArrayList
(tmp)); dfs(i + 1, num, tmp, res); tmp.remove(tmp.size() - 1); } } }}