考虑一个这样的问题,对于一个5块钱,你有1,2,3,4,5块钱,任意多张,问有多少个不同方案数,把5块钱找开
枚举和等于5的序列即可,如果 2 3 和 3 2 是同一组,那么每次都从0位置开始枚举,如果 2 3 和 3 2不是同一组,那么,枚举开始位置必须为上一个位置。
代码如下
#include"pch.h" #include <string> #include<iostream> #include<map> #include<memory.h> #include<vector> #include<algorithm> #include<queue> #include<vector> #include<stack> #include<math.h> #include<iomanip> #include<bitset> #include"math.h" namespace cc { using std::cout; using std::endl; using std::cin; using std::map; using std::vector; using std::string; using std::sort; using std::priority_queue; using std::vector; using std::swap; using std::stack; using std::queue; using std::bitset; int total = 0; constexpr int N = 5; int dir[] = {1,2,3,4,5}; int n; int ans[N]; void dfsNotRepeat(int t,int pre,int index) { if (t == 0) { for (int i = 0;i < index;i++) cout << " " << ans[i]; cout << endl; return; } else { for (int i = pre;i < n;i++) { if (dir[i] <= t) { ans[index] = dir[i]; dfsNotRepeat(t-dir[i],i,index+1); } } } } void dfsRepeat(int t, int pre, int index) { if (t == 0) { for (int i = 0;i < index;i++) cout << " " << ans[i]; cout << endl; return; } else { for (int i = 0;i < n;i++) { if (dir[i] <= t) { ans[index] = dir[i]; dfsRepeat(t - dir[i], i, index + 1); } } } } /** * *不重复的枚举 * */ void solve() { n = 5; dfsNotRepeat(5,0,0); cout << endl << endl << endl; dfsRepeat(5,0,0); } }; int main() { #ifndef ONLINE_JUDGE freopen("d://1.text", "r", stdin); //freopen("d://1.out", "w", stdout); #endif // !ONLINE_JUDGE cc::solve(); return 0; }