/**
* find k from n, to make sum(k) equals m.
*
*/
public class SubSumEquals {
public void containValue(int[] a, int value){
assert(true);
for(int i=1; i<=a.length; i++){
int[] b = new int[i];
find(a, a.length, i, value, b);
}
}
private void find(int[] a, int n, int m, int value, int[] b){
assert(true);
for(int i=n; i>=m; i--){
b[m-1] = i - 1 ;
if(m > 1){
find(a, i-1, m-1, value, b);
}else{
testEquals(a, b, value);
}
}
}
private void testEquals(int[] a, int[] b, int value){
assert(true);
int sum = 0;
for(int i=0; i<b.length; i++){
sum += a[b[i]];
}
if(sum == value){
for(int j=0; j<b.length; j++){
System.out.print(a[b[j]] + " ");
}
System.out.println();
}
}
/**
* @param args
*/
public static void main(String[] args) {
int[] a = {3,2,4,3,6};
SubSumEquals sse = new SubSumEquals();
sse.containValue(a, 6);
}
}
从n个数挑k个,和等于m
最新推荐文章于 2021-05-21 10:22:19 发布