还是BT方法,而且这道题应该在77之前做会更好,因为这个是最初的模型。每次用interface往下走的时候,都要把interface里传入的item 的副本加入到result里去,也再次说明了,for() loop里面的interface里都是带着上一层传过来的item 进入到下一层。
代码如下: conditioning (which is no condition in this case) + BT core
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if(nums.length==0) return result;
List<Integer> item = new ArrayList<>();
//result.add(new ArrayList<>(item));
backtracking(nums, result, item, 0);
return result;
}
private void backtracking(int[] nums, List<List<Integer>> result, List<Integer> item, int start){
result.add(new ArrayList<Integer>(item)); // damn good!!
for(int i=start; i<nums.length; i++){ // for every iteration, the up bound is fixed, no change for that
item.add(nums[i]);
backtracking(nums, result, item, i+1);
item.remove(item.size()-1);
}
}
}TODO: 当输入是String,要求输出是List<String>时,怎么操作?
本文详细介绍了使用回溯法生成给定数组的所有可能子集的方法。通过递归地添加元素并回溯,确保每个子集都被正确生成。文章提供了完整的Java实现代码,并解释了关键步骤。

1048

被折叠的 条评论
为什么被折叠?



