print all unique solution to split number n, given choice of 1 3 5 10
for example if n is 4
{1, 1, 1, 1}
{1, 3}
思路:用DFS肯定可以求解,但需要遍历所有可能,进行剪纸之后用递推实现。主要剪枝思想,后一个数一定要大于等于前一个数
- #include <iostream>
- #include <vector>
- using namespace std;
- vector<vector<int> > res;
- vector<int> cur;
- void getAllPath(vector<int> &base,int last,int n){
- if(n==0) {
- res.push_back(cur);
- return;
- }
- for(int i=0;i<base.size();i++) {
- if(base[i]>n) return;
- if(base[i]<last) continue;
- cur.push_back(base[i]);
- getAllPath(base,base[i],n-base[i]);
- cur.pop_back();
- }
- }
- int main() {
- vector<int> base(4);
- base[0] = 1;
- base[1] = 3;
- base[2] = 5;
- base[3] = 10;
- getAllPath(base,0,8);
- for(int i=0;i<res.size();i++) {
- for(int j=0;j<res[i].size();j++) {
- cout<<res[i][j]<<"\t";
- }
- cout<<endl;
- }
- return 0;
- }
时间: 2024-11-03 16:30:41