本题是回溯法的基本应用,深度优先遍历,使用递归实现。
class Solution { public: int x[10000]; vector<vector<int>> R; int n; //t当前查询的位置 void BackTrack(vector<int> nums, int t) { if (t >= n)//达到叶子节点 { vector<int> V; for (int i = 0; i < n; i++) { if (x[i] == 1) { V.push_back(nums[i]); } } R.push_back(V); return; } x[t] = 0; BackTrack(nums, t + 1); x[t] = 1; BackTrack(nums, t + 1); } vector<vector<int>> subsets(vector<int>& nums) { n = nums.size(); memset(x, 0, sizeof(x)); BackTrack(nums, 0); return R; } };
补充一个python版本:
1 class Solution: 2 def __init__(self): 3 self.L = list() 4 self.N = 0 5 6 def backTrack(self,nums,index,l): 7 if index >= self.N: 8 self.L.append(l[:]) 9 return 10 l.append(nums[index]) 11 self.backTrack(nums,index+1,l) 12 13 l.pop(-1) 14 self.backTrack(nums,index+1,l) 15 16 def subsets(self, nums: 'List[int]') -> 'List[List[int]]': 17 self.N = len(nums) 18 l = list() 19 self.backTrack(nums,0,l) 20 return self.L