//执行结果
5050
```
public Knapsack(int[] weights){
this.weights = weights;
selects = new boolean[weights.length];
}
/**
* 找出符合承重重量的组合
* @param total 总重量
* @param index 可供选择的重量下标
*/
public void knapsack(int total,int index){
if(total < 0 || total > 0 && index >= weights.length){
return;//没找到解决办法,直接返回
}
if(total == 0){//总重量为0,则找到解决办法了
for(int i = 0 ; i < index ; i++){
if(selects[i] == true){
System.out.println(weights[i]+" ");
}
}
System.out.println();
return;
}
selects[index] = true;
knapsack(total-weights[index], index+1);
selects[index] = false;
knapsack(total, index+1);
}
}
```测试结果public static void main(String[] args) {
int array[] = {11,9,7,6,5};
int total = 20;
Knapsack k = new Knapsack(array);
k.knapsack(total, 0);
}
public Combination(char[] persons){
this.persons = persons;
selects = new boolean[persons.length];
}
public void showTeams(int teamNumber){
combination(teamNumber,0);
}
/**
*
* @param teamNumber 需要选择的队员数
* @param index 从第几个队员开始选择
*/
public void combination(int teamNumber,int index){
if(teamNumber == 0){//当teamNumber=0时,找到一组
for(int i = 0 ; i < selects.length ; i++){
if(selects[i] == true){
System.out.print(persons[i]+" ");
}
}
System.out.println();
return;
}
//index超过组中人员总数,表示未找到
if(index >= persons.length ){
return;
}
selects[index] = true;
combination(teamNumber-1, index+1);
selects[index] = false;
combination(teamNumber, index+1);
}
}
```测试结果public static void main(String[] args) {
char[] persons = {'A','B','C','D','E'};
Combination cb = new Combination(persons);
cb.showTeams(3);
}
// hasSolvedList 可以理解成一个 Map,key 是 n,value 是 f(n)
if (hasSolvedList.containsKey(n)) {
return hasSovledList.get(n);
}
int ret = f(n-1) + f(n-2);
hasSovledList.put(n, ret);
return ret;
}
```
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有