波波老师好,我在做78号问题的时候,自己觉得用上了剪枝,但是执行用时没有提高,希望老师看下我的代码
LeetCode 78题地址:https://leetcode-cn.com/problems/subsets/submissions/
下面是我的代码:
class Solution {
public List<List<Integer>> subsets(int[] nums) {
if (nums == null ||nums.length == 0) return new ArrayList<>();
Arrays.sort(nums);
List<List<Integer>> res = sets(nums);
res.add(new ArrayList<>());
return res;
}
private List<List<Integer>> sets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
// 终止条件
if (nums == null || nums.length == 0) return res;
int len = nums.length;
if (len == 1) {
List list = new ArrayList();
list.add(nums[0]);
res.add(list);
return res;
}
// 递归条件
for (int i = 0; i < len; i++) {
List list = new ArrayList();
list.add(nums[i]);
res.add(list);
if (i + 1 == len) { // 剪枝操作
break;
}
int[] newDate = newDate(nums, i, len);
List<List<Integer>> result = sets(newDate);
for (int j = 0; j < result.size(); j++) {
result.get(j).add(nums[i]);
res.add(result.get(j));
}
}
return res;
}
private int[] newDate(int[] nums, int i, int len) {
int[] newDate = new int[len - i - 1];
for (int j = i + 1; j < len; j++) {
newDate[j - i - 1] = nums[j];
}
return newDate;
}
}
登录后可查看更多问答,登录/注册