怎样建设网站空间,建筑工程网上办事大厅,网页设计项目描述怎么写,网站添加icp信息题目
给你一个整数数组 nums #xff0c;数组中的元素 互不相同 。返回该数组所有可能的子集#xff08;幂集#xff09;。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1#xff1a;
输入#xff1a;nums [1,2,3]
输出#xff1a;[[],[1],[2],[1…题目
给你一个整数数组 nums 数组中的元素 互不相同 。返回该数组所有可能的子集幂集。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1
输入nums [1,2,3]
输出[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]示例 2
输入nums [0]
输出[[],[0]]提示
1 nums.length 10-10 nums[i] 10nums 中的所有元素 互不相同 解答
源代码
class Solution {public ListListInteger subsets(int[] nums) {ListListInteger res new ArrayListListInteger();ListInteger combine new ArrayListInteger();dfs(res, combine, nums, 0);return res;}public void dfs(ListListInteger res, ListInteger combine, int[] nums, int index) {res.add(new ArrayListInteger(combine));if (index nums.length) {return;}for (int i index; i nums.length; i) {combine.add(nums[i]);dfs(res, combine, nums, i 1);combine.remove(combine.size() - 1);}}
}
总结
经典的回溯算法这道题要另外注意一下不能到索引结束再添加元素要每次更新索引都需要添加元素。