Given two integers n and k, return all possible combinations ofk numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
dfs+回溯
public List> combine(int n, int k) {
List> ret = new ArrayList<>();
List tmp = new ArrayList<>();
combineCore(n, k, ret, tmp, 1);
System.out.println(ret);
return ret;
}
private void combineCore(int n, int k, List> ret, List tmp, int idx) {
// 求指定数目组合
// 用k判断而非idx
if (k <= 0) {
ret.add(new ArrayList<>(tmp));
return;
}
for (int i = idx; i <= n; i++) {
tmp.add(i);
// 传入i+1非重复
combineCore(n, k - 1, ret, tmp, i + 1);
tmp.remove(tmp.size() - 1);
}
}
Given a set of distinct integers,nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3]
, a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
当前层的集合 = 上一层的集合 + 上一层的集合加入当前层处理的元素得到的所有集合(其中树根是空集),因此可以从第二层开始(第一层是空集合)迭代地求最后一层的所有集合(即叶子节点)
39. Combination Sum
40. Combination Sum II
216. Combination Sum III
377. Combination Sum IV
public List> subsets(int[] nums) {
List> res = new ArrayList>();
List tmp = new ArrayList<>();
// 排序可以避免重复,然后结果可以安装顺序输出
// Arrays.sort(nums);//此题不需要排序
dfsCore(res, 0, tmp, nums);
System.out.println(res);
return res;
}
private void dfsCore(List> res, int curIdx, List tmp, int[] nums) {
if (curIdx <= nums.length) {
res.add(new ArrayList(tmp));
}
// 下标从curIdx开始
for (int i = curIdx; i < nums.length; i++) {
tmp.add(nums[i]);
dfsCore(res, i + 1, tmp, nums);
tmp.remove(tmp.size() - 1);
}
}
public List> subsets(int[] nums) {
List> res = new ArrayList>();
List tmp = new ArrayList<>();
// 排序可以避免重复,然后结果可以安装顺序输出
// Arrays.sort(nums);//此题不需要排序
dfsCore2(res, 0, tmp, nums);
System.out.println(res);
return res;
}
// 组合有两种情况,要么加入nums[curIdx],要么不加入
private void dfsCore2(List> res, int curIdx, List tmp, int[] nums) {
// 注意退出条件的不同
if (curIdx == nums.length) {
res.add(new ArrayList(tmp));
return;
}
// 不加入nums[curIdx]
dfsCore2(res, curIdx + 1, tmp, nums);
// 加入nums[curIdx]
tmp.add(nums[curIdx]);
dfsCore2(res, curIdx + 1, tmp, nums);
// 回溯
tmp.remove(tmp.size() - 1);
}
Given a collection of integers that might contain duplicates,nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2]
, a solution is:
集合有重复元素
1、sort函数对集合排序
2、去重
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
public List> subsetsWithDup(int[] nums) {
List> res = new ArrayList>();
List tmp = new ArrayList<>();
// 排序可以避免重复,然后结果可以安装顺序输出
Arrays.sort(nums);
dfsCore(res, 0, tmp, nums);
System.out.println(res);
return res;
}
private void dfsCore(List> res,
int curIdx, List tmp, int[] nums) {
if (curIdx <= nums.length) {
res.add(new ArrayList(tmp));
}
for (int i = curIdx; i < nums.length; i++) {
if (i > curIdx && nums[i] == nums[i - 1])
// deal with dupicate
continue;
tmp.add(nums[i]);
dfsCore(res, i + 1, tmp, nums);
tmp.remove(tmp.size() - 1);
}
}