回溯 02
LeetCode 78
https://leetcode-cn.com/problems/subsets/
代码如下
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
backtrack(0, nums, res, new ArrayList<Integer>());
return res;
}
public void backtrack(int index, int[] nums, List<List<Integer>> res, ArrayList<Integer> temp) {
res.add(new ArrayList<>(temp)); // 每一次递归下一个值,都存入子集中
for (int j = index; j < nums.length; j++) {
temp.add(nums[j]);
backtrack(j + 1, nums, res, temp);
temp.remove(temp.size() - 1); // 回溯回原来的状态
}
}
}
网友评论