因此,他们总给定的总和打印所有方法,总结n个整数。 [英] Print all ways to sum n integers so that they total a given sum.

查看:98
本文介绍了因此,他们总给定的总和打印所有方法,总结n个整数。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拿出,将打印出所有可能的方式,使他们总给定值总结N个整数算法。

为例。打印所有方法,总结4个整数,使他们总结为5。

结果应该是这样的:

  5 0 0 0
4 1 0 0
3 2 0 0
3 1 1 0
2 3 0 0
2 2 1 0
2 1 2 0
2 1 1 1
1 4 0 0
1 3 1 0
1 2 2 0
1 2 1 1
1 1 3 0
1 1 2 1
1 1 1 2
 

解决方案

这是基于关闭Alinium的code。
我修改了它,所以它打印出所有可能的组合,因为他已经完成了所有的排列组合。
另外,我不认为你需要当n =循环1,因为在这种情况下,只有一个数字应引起总和相等的值。
各种其它修改来获得边界情况的工作。

 高清之和(N,值):
    ARR = [0] * N#创建一个大小为n的数组,充满了零
    sumRecursive(N,价值,O,N,ARR);

高清sumRecursive(N,价值,sumSoFar,顶层,编曲):
    如果n == 1:
        如果sumSoFar< =值:
            了#make肯定这是按升序(或仅级)
            如果顶层== 1(价值 -  sumSoFar> = ARR [-2]):
                ARR [( -  1)] =价值 -  sumSoFar #put它在n_th ARR的最后一个索引
                打印ARR
    ELIF N'GT; 0:
        了#make确保其按升序排列
        启动= 0
        如果(N =顶层!):
            开始= ARR [( -  1 * N)-1]这个元素之前#系统的价值

        因为我的范围(启动,值+ 1):#I =启动...价值
            ARR [( -  1 * N)] =#我把我的n_th ARR的最后一个索引
            sumRecursive(N-1,价值,sumSoFar + I,顶层,ARR)
 

乳宁款项(4,5)返回:
[0,0,0,5]
[0,0,1,4]
[0,0,2,3]
[0,1,1,3]
[1,1,1,2]

I'm trying to come up with an algorithm that will print out all possible ways to sum N integers so that they total a given value.

Example. Print all ways to sum 4 integers so that they sum up to be 5.

Result should be something like:

5 0 0 0
4 1 0 0
3 2 0 0
3 1 1 0
2 3 0 0
2 2 1 0
2 1 2 0
2 1 1 1
1 4 0 0
1 3 1 0 
1 2 2 0
1 2 1 1
1 1 3 0
1 1 2 1
1 1 1 2

解决方案

This is based off Alinium's code.
I modified it so it prints out all the possible combinations, since his already does all the permutations.
Also, I don't think you need the for loop when n=1, because in that case, only one number should cause the sum to equal value.
Various other modifications to get boundary cases to work.

def sum(n, value):
    arr = [0]*n  # create an array of size n, filled with zeroes
    sumRecursive(n, value, 0, n, arr);

def sumRecursive(n, value, sumSoFar, topLevel, arr):
    if n == 1:
        if sumSoFar <= value:
            #Make sure it's in ascending order (or only level)
            if topLevel == 1 or (value - sumSoFar >= arr[-2]):
                arr[(-1)] = value - sumSoFar #put it in the n_th last index of arr
                print arr
    elif n > 0:
        #Make sure it's in ascending order
        start = 0
        if (n != topLevel):
            start = arr[(-1*n)-1]   #the value before this element

        for i in range(start, value+1): # i = start...value
            arr[(-1*n)] = i  # put i in the n_th last index of arr
            sumRecursive(n-1, value, sumSoFar + i, topLevel, arr)

Runing sums(4, 5) returns:
[0, 0, 0, 5]
[0, 0, 1, 4]
[0, 0, 2, 3]
[0, 1, 1, 3]
[1, 1, 1, 2]

这篇关于因此,他们总给定的总和打印所有方法,总结n个整数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆