Given an integer, return all sequences of numbers that sum to it

Q:

Given an integer, return all sequences of numbers that sum to it. (Example: 3 -> (1, 2), (2, 1), (1, 1, 1)). 

A: 

 

class CalcSequenceNumber
{
private:
    static void print(int values[], int n)
    {
        for (int i = 0; i < n; ++i) // n may be less then length of values[]
        {
            cout << " " << values[i];
        }
        cout << endl;
    }

    static void decompose(int x, int values[], int index) 
    {
        if(x == 0) 
        {
            print(values, index);
            return ;
        }

        // this algorithm is similar to permutation, charge coin, etc.
        for (int i = 1; i < x; i++) 
        {
            values[index] = i;
            decompose(x - i, values, index + 1);
        }

        // special case for non-zero component
        if (index > 0)  // when i >= x, we need to fill the next number to make (previous numbers + next number == input number)
        {
            values[index] = x;
            decompose(0, values, index + 1);
        }
    }


public:
    static void decompose(int x) 
    {
        cout << "The input number is " << x << " :" << endl;

        int* values = new int[x];
        decompose(x, values, 0);
        delete[] values;
    }
};

samples:

The input number is 3 :
 1 1 1
 1 2
 2 1
The input number is 5 :
 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

非递归算法:

这个方法是根据上面的输出例了,倒推出来的,但非常适用于这道题目

C/C++

void CalcSequenceNumber(int n)
{
    cout << "The input number is " << n << " :" << endl;

    vector<int> v(n);
    int i = 0;
    while (i < n) v[i++] = 1;

    while (1)
    {
        int j = 0; while (j < v.size()) cout << " " << v[j++]; cout << endl;

        if (v[v.size() - 1] == 1)
        {
            v.pop_back();
            v[v.size() - 1] += 1;
        }
        else
        {
            v[v.size() - 2] += 1;
            int k = v[v.size() - 1] - 1;
            v[v.size() - 1] = 1; k--;
            while (k-- > 0) v.push_back(1);
        }

        if (v[0] == n)
            break;
    }
}

感谢 csdn 网友 (tkminigame), python 代码

def foo3():
    l = [1]*n
    while True:
        print (*l)

        if l[-1] == 1:
            l.pop()
            l[-1] += 1
        else:
            l[-2] += 1
            l[-1:] = [1]*(l[-1] - 1)
        
        if l[0] == n:
            break

  

 

原文链接: https://www.cnblogs.com/yayagamer/archive/2013/01/23/2873370.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    Given an integer, return all sequences of numbers that sum to it

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/76509

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午5:32
下一篇 2023年2月9日 下午5:34

相关推荐