OR64. 求和
描述
输入两个整数 n 和 m,从数列1,2,3.......n 中随意取几个数,使其和等于 m ,要求将其中所有的可能组合列出来输入描述
每个测试输入包含2个整数,n和m输出描述
按每个组合的字典序排列输出,每行输出一种组合示例1
输入:
5 5
输出:
1 4<br/>2 3<br/>5
C++ 解法, 执行用时: 1ms, 内存消耗: 220KB, 提交时间: 2017-06-11
#include<iostream> #include<string> #include<algorithm> #include<vector> using namespace std; void dfs(vector<int>& curp, vector<vector<int>>& rst, int curn, int n, int tar){ if (tar == 0){ rst.push_back(curp); } for (int i = curn; i <= n; i++){ curp.push_back(i); dfs(curp, rst, i + 1, n, tar - i); curp.pop_back(); } } int main(){ int n, m; cin >> n >> m; vector<int> curp; vector<vector<int>> rst; dfs(curp, rst, 1,n, m); for (int i = 0; i < rst.size(); i++){ cout << rst[i][0]; for (int j = 1; j < rst[i].size(); j++){ cout << " "<<rst[i][j]; } cout << endl; } return 0; }
C++ 解法, 执行用时: 1ms, 内存消耗: 364KB, 提交时间: 2017-09-03
#include<iostream> #include<vector> using namespace std; void helper(vector<int>& num, int begin, int n, int m) { if (m == 0) { for (int i = 0; i < num.size(); i++) { i == 0 ? cout << num[i] : cout << " " << num[i]; } cout << endl; } for (int i = begin; i <= n&&i <= m; i++) { num.push_back(i); helper(num, i + 1, n, m - i); num.pop_back(); } } int main() { int n, m; while (cin >> n >> m) { vector<int> num; helper(num, 1, n, m); } return 0; }