【回溯算法】7-7 整数分解为若干项之和

 【回溯算法】7-7 整数分解为若干项之和_第1张图片

void dfs(vector& way, int target, int last, int sum) {
    if(target < sum) return;
    if(target == sum) {
        ans.push_back(way);
        return;
    }
    for(int i = 1; i <= target; i++) {
        if(last > i) continue;
        if(sum + i > target) break;
        way.push_back(i);
        dfs(way, target, i, sum + i);
        way.pop_back();
    }
}

主要说一下我这里的剪枝操作

=> 规定每次放进容器的数字大于等于上一次放进去的数字 

#include 
using namespace std;

vector> ans;

void dfs(vector& way, int target, int last, int sum) {
    if(target < sum) return;
    if(target == sum) {
        ans.push_back(way);
        return;
    }
    for(int i = 1; i <= target; i++) {
        if(last > i) continue;
        if(sum + i > target) break;
        way.push_back(i);
        dfs(way, target, i, sum + i);
        way.pop_back();
    }
}

int main() {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        vector way;
        way.push_back(i);
        dfs(way, n, i, i);
    }
    int count = 0;
    for(int i = 0; i < ans.size(); i++) {
        for (int j = 0; j < ans[i].size(); j++) {
            if(!j) cout << n << '=' << ans[i][j];
            else cout << '+' << ans[i][j];
        }
        count++;
        if(count % 4 == 0) cout << endl;
        else if(i != ans.size() - 1) cout << ';';
    }
    return 0;
}

你可能感兴趣的:(Data,Structure,&,Algorithm,算法,c++,深度优先)