UVALive 6661 解题心得
原题:
https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4673
题目大意:
求从不超过 N 的正整数当中选取 K 个不同的数字,组成和为 S 的方法数。
1 <= N <= 20 1 <= K<= 10 1 <= S <= 155
找好约束条件和结束条件就可以使用dfs轻松做出来
约束条件:cur_sum+i == sum&&dep==k
结束条件:cur_sum == sum,
我的代码:
#include<iostream> #include<cstdio> using namespace std; int n, k, sum; int cnt = 0; int depth=0; void dfs(int dep, int cur_num, int cur_sum) { //depth++; if (cur_sum == sum) return; for (int i = cur_num; i <= n; i++) { if (cur_sum+i>sum) return; if (cur_sum+i == sum&&dep==k) { cnt++; return; } dfs(dep + 1, i + 1, cur_sum + i); } } int main() { while (cin >> n >> k >> sum&&n != 0) { depth = 0; cnt = 0; dfs(1, 1, 0); cout << cnt << endl; } return 0; }