原题链接:78. Subsets
"Thought 1-java" backtracking algorithm | Recursive implementation
This method is implemented by backtracking algorithm, the basic form of backtracking algorithm is "recursive + cycle", because the loop is nested recursively, recursion contains loops, which makes backtracking more difficult to understand than the general recursive and simple loops, in fact, we are familiar with its basic form, we will find such an algorithm is not very difficult. Each element in the original array has two states: exists and does not exist.
① the outer loop adds element nums[i to the middle set temp, so that the element is in an existing state
② begins recursion, and recursion carries the temp with the new element, and the next loop starts with the next of the I element, so the update I value in recursion is I + 1
③ removes this from the intermediate set temp so that the element is in a nonexistent state
public class Solution {public
list<list<integer>> subsets (int[] nums) {
List<list<integer >> res = new arraylist<list<integer>> ();
list<integer> temp = new arraylist<integer> ();
DFS (res, temp, nums, 0);
return res;
}
private void Dfs (list<list<integer>> res, list<integer> temp, int[] nums, Int j) {
Res.add (new Arra Ylist<integer> (temp));
for (int i = j; i < Nums.length; i++) {
temp.add (nums[i)); ① joins Nums[i]
dfs (res, temp, nums, i + 1); ② recursive
temp.remove (Temp.size ()-1); ③ removal of Nums[i]}}
10/10 Test cases passed. Runtime:2 ms Your Runtime beats 61.73% of javasubmissions.
"Thinking 2-java, Python" combination | non-recursive implementation
This approach is a combination of ways
① the outermost loop takes each element num out of the nums array
② inner Loops Remove each intermediate result set from the original result sets and add the NUM element to each intermediate result set
③ Add num to each intermediate result set
④ adds a new intermediate result set to the results set
public class Solution {public
list<list<integer>> subsets (int[] nums) {
List<list<integer >> res = new arraylist<list<integer>> ();
Res.add (New arraylist<integer> ());
for (int num:nums) { //① remove each element
int size = Res.size () from the array);
for (int i = 0; i < size; i++) {
list<integer> temp = new Arraylist<> (Res.get (i)); ② out the intermediate result set
temp.add (num); ③ the NUM into the intermediate result set
res.add (temp); ④ join to result set} return
res;
}
10/10 Test cases passed. Runtime:2 ms Your Runtime beats 61.73% of javasubmissions.
Class Solution (object):
def subsets (Self, nums):
"" "
: Type Nums:list[int]
: Rtype:list[list[int]] ""
res = [[]] for
num in nums: for
temp in res[:]:
x = temp[:]
x.append (num)
res.append (x ) Return
Res
10/10 Test cases passed. runtime:52 ms Your Runtime beats 98.24% of pythonsubmissions.