# 长度为n的数组，取其中k个，要求和为sum,求有多少种取法

public class CountKequalSum {
public static void main(String[] args) {
int[] arr = {1,3,2,2};
int k = 2;
int sum = 4;
int r = solution(arr,arr.length-1,k,sum);
System.out.println(r);
}
static int solution(int[] arr,int end,int k, int sum){ //arr数组中，前end个数，取k个，和为sum的组合种类（取法）
if(end+1 < k||end<0||k<0)
return 0;
if(sum == 0 && k==0)
return 1;
if(k==0 && sum!=0)
return 0;

int[][] result = new int[2][end+1];
result[0][k-1] = 0;
result[1][k-1] = init(arr,end, k, sum);

for (int i = k; i <= end; i++) {                         //状态递推公式
result[0][i] = result[0][i-1]+result[1][i-1];        //result[0][i] 表示第i个数arr[i]不取时，有多少种组合
result[1][i] = solution(arr, i-1, k-1, sum-arr[i]);    //result[1][i]  表示第i个数取时，有多少中组合
}
return result[0][end]+result[1][end];
}
static int init(int[] arr,int end, int k, int sum){         //初值初始化计算
if(sum == 0 && k==0)
return 1;
if( end < 0|| k < 1 ||end+1 < k)
return 0;
int count = 0;
for(int i = 0;i < k; i++){
count += arr[i];
}
if(count == sum)
return 1;
return 0;
}

}


package 算法;

public class CountKequalSumRecursion {
public static void main(String[] args) {
int[] arr = {1,3,2,2};
int k = 2;
int sum = 4;
System.out.println(solution(arr, 0, k, sum));

}
static int solution(int[] arr,int begin, int k , int sum){
if(begin > arr.length)
return 0;
if(k==0 && sum != 0)
return 0;
if(k == 0 && sum == 0)
return 1;
if(begin >= arr.length)
return 0;
return solution(arr, begin+1, k-1,sum-arr[begin])+solution(arr, begin+1, k, sum);//第i个选，或者第i个不选，两者相加
}

}