手机网站产品展示模板,做网站襄樊,网页美工实训总结,北京建设集团招聘信息网站题目#xff1a;
给你一个整数数组 nums #xff0c;数组中的元素 互不相同 。返回该数组所有可能的 子集#xff08;幂集#xff09;。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1#xff1a; 输入#xff1a;nums [1,2,3] 输出#xff1a;[[…题目
给你一个整数数组 nums 数组中的元素 互不相同 。返回该数组所有可能的 子集幂集。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1 输入nums [1,2,3] 输出[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2 输入nums [0] 输出[[],[0]]
思路
回溯法选择数组元素如果数组元素全都选择完了就添加到结果集里面回溯移除最后添加的数组元素移除后再次进行递归添加新的子集
代码
class LeetCode78 {//存放结果集ListListInteger resultList new ArrayList();//存放已经被选中的数据ListInteger list new ArrayList(); public ListListInteger subsets(int[] nums) {//回溯法 dfs (0, nums);return resultList;}public void dfs (int cur, int[] nums) {//如果全都选择完了就添加到结果集里面if (cur nums.length) {resultList.add(new ArrayListInteger(list));return;}//选择数组元素list.add( nums[cur]);//递归dfs(cur1, nums);//回溯移除刚添加的(也就是最后一个)元素以便后面再重新选择list.remove( list.size()-1);// 移除后一个元素后,再次进行递归添加新的子集到list中dfs(cur1, nums);}}