Getting all possible sums that add up to a given number

前端 未结 6 1600
灰色年华
灰色年华 2020-12-01 07:17

I\'m making an math app for the android. In one of these fields the user can enter an int (no digits and above 0). The idea is to get all possible sums that make this int, w

6条回答
  •  伪装坚强ぢ
    2020-12-01 07:55

    All of these solutions seem a little complex. This can be achieved by simply "incrementing" a list initialized to contain 1's=N.

    If people don't mind converting from c++, the following algorithm produces the needed output.

    bool next(vector& counts) {
        if(counts.size() == 1)
            return false;
    
        //increment one before the back
        ++counts[counts.size() - 2];
    
        //spread the back into all ones
        if(counts.back() == 1)
            counts.pop_back();
        else {
            //reset this to 1's
            unsigned ones = counts.back() - 1;
            counts.pop_back();
            counts.resize(counts.size() + ones, 1);
        }
        return true;
    }
    
    void print_list(vector& list) {
        cout << "[";
        for(unsigned i = 0; i < list.size(); ++i) {
            cout << list[i];
            if(i < list.size() - 1)
                cout << ", ";
        }
        cout << "]\n";
    }
    
    int main() {
        unsigned N = 5;
        vector counts(N, 1);
        do {
            print_list(counts);
        } while(next(counts));
        return 0;
    }
    

    for N=5 the algorithm gives the following

    [1, 1, 1, 1, 1]
    [1, 1, 1, 2]
    [1, 1, 2, 1]
    [1, 1, 3]
    [1, 2, 1, 1]
    [1, 2, 2]
    [1, 3, 1]
    [1, 4]
    [2, 1, 1, 1]
    [2, 1, 2]
    [2, 2, 1]
    [2, 3]
    [3, 1, 1]
    [3, 2]
    [4, 1]
    [5]
    

提交回复
热议问题