Leetcode subset
Given a set of distinct integers, S, return all possible subsets.
Note:
- Elements in a subset must is 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,3], [+] , [2,3], [up ], []]
Topic Analysis:
This return all possible question can use the BFS method to solve the idea is to first sort the array (because the title is required to be non-descending)
Then the idea is to read the number from NUM, then save it to the list in arraylist<integer>, and then save the list to the arraylist<arraylist<integer>> Res.
The order is like this [], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]
Remember border detection
1 Public classSolution {2 Public Staticlist<list<integer>> Subsets (int[] S) {3list<list<integer>> res =NewArraylist<list<integer>>();4 if(S = =NULL|| S.length = = 0)5 returnRes;6 Arrays.sort (S);7arraylist<integer> list =NewArraylist<integer>();8DFS (res, list, S, 0);9 returnRes;Ten } One Public Static voidDFS (list<list<integer>> res, arraylist<integer> List,int[] S,intPOS) { ARes.add (NewArraylist<integer>(list)); - for(inti = pos; i < s.length; i++){ - List.add (S[i]); theDFS (res, list, S, i+1); -List.remove (List.size ()-1); - } - } +}
Leetcode permutations
Given A collection of numbers, return all possible permutations.
For example,
[1,2,3]
The following permutations:
[1,2,3]
,,,,, [1,3,2]
[2,1,3]
[2,3,1]
[3,1,2]
and [3,2,1]
.
Topic Analysis:
This problem is a typical DFS ~ directly with the DFS model is good ~ as to detect whether an element of an array is used in this case, create a new Boolean array to detect it!
Public classSolution { Public StaticList<list<integer>> Permute (int[] num) {List<List<Integer>> res =NewArraylist<list<integer>>(); ArrayList<Integer> list =NewArraylist<integer>(); Boolean[] flag =New Boolean[Num.length]; DFS (RES, list, num, flag); returnRes; } Public Static voidDFS (list<list<integer>> res, arraylist<integer> List,int[] num,Boolean[] flag) { if(list.size () = =num.length) {Res.add (NewArraylist<integer>(list)); return; } for(inti = 0; i < num.length; i++){ if(!Flag[i]) {Flag[i]=true; List.add (Num[i]); DFS (RES, list, num, flag); List.remove (List.size ()-1); Flag[i]=false; } } }}
Two problems of DFS solution Leetcode permutations & Leetcode Subset