用回溯算法解决集合问题(Java实现)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
⽤回溯算法解决集合问题(Java实现)1.1题⽬:组合
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
⽰例:
输⼊: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
解决代码:
class Solution {
int n;
int k;
List<List<Integer>> res = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
this.n = n;
this.k = k;
middleMeth(1,new LinkedList<Integer>());
return res;
}
public void middleMeth(int temp,LinkedList<Integer> list){
if(list.size() == k){
res.add(new LinkedList(list));
}
for(int i = temp; i < n + 1 ;++i){
list.add(i);
middleMeth(i + 1,list);
list.removeLast();
}
}
}
1.2题⽬:⼦集
给定⼀组不含重复元素的整数数组 nums,返回该数组所有可能的⼦集(幂集)。
说明:解集不能包含重复的⼦集。
⽰例:
输⼊: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
解决代码:
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
MethodMiddle(0,nums,res,new ArrayList<>());
return res;
}
public void MethodMiddle(int i,int[] nums,List<List<Integer>> res,List<Integer> list){
res.add(new ArrayList<Integer>(list));
for(int j = i;j < nums.length;j++){
list.add(nums[j]);
MethodMiddle(j + 1,nums,res,list);
list.remove(list.size() - 1);
}
}
}
1.3题⽬:⼦集II
给定⼀个可能包含重复元素的整数数组 nums,返回该数组所有可能的⼦集(幂集)。
说明:解集不能包含重复的⼦集。
⽰例:
输⼊: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
解决代码:
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
MethodMidd(0,nums,res,new ArrayList<>());
return res;
}
public void MethodMidd(int index,int[] nums,List<List<Integer>> res,List<Integer> list){
res.add(new ArrayList<>(list));
for(int i = index;i < nums.length;i++){
if(i > index && nums[i - 1] == nums[i]){
continue;
}
list.add(nums[i]);
MethodMidd(i + 1,nums,res,list);
list.remove(list.size() - 1);
}
}
}。