Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
Solution:Backtracking(DFS)
總結(jié)見:http://www.reibang.com/p/883fdda93a66
其實就是backtrack的simple組合問題况凉,套路ok购笆,沒有終止條件悠汽,每一步都add到cur_res.
思路:回溯法想罕,類似深度優(yōu)先進行組合惊奇,cur_result數(shù)組保持用當前嘗試的結(jié)果,并按照深度優(yōu)先次序依次將組合結(jié)果加入到result_list中耍共,DFS到底后 step back (通過remove 當前cur_result的最后一位)乃沙,換下一個嘗試組合,后繼續(xù)DFS重復(fù)此過程,實現(xiàn)上采用遞歸方式隅肥。
例:input: [1, 2, 3, 4]
輸出:
[]
[1] [12] [123] [1234] [124] [13] [134] [14]
[2] [23] [234] [24]
[3] [34]
[4]
Time Complexity: O(2^n) ? (Not Sure)
Space Complexity(不算result的話): O(2n) : n是遞歸緩存的cur_result + n是緩存了n層的普通變量O(1) ? (Not Sure)
Solution Code:
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> cur_res = new ArrayList<>();
backtrack(nums, 0, cur_res, result);
return result;
}
private void backtrack(int nums[], int start, List<Integer> cur_res, List<List<Integer>> result) {
result.add(new ArrayList<>(cur_res));
for(int i = start; i < nums.length; i++) {
cur_res.add(nums[i]);
backtrack(nums, i + 1, cur_res, result);
cur_res.remove(cur_res.size() - 1);
}
}
}