因此,他们总给定的总和打印所有方法,总结n个整数。整数、总和、方法

2023-09-11 05:24:07 作者:心里的那道疤╮

我想拿出,将打印出所有可能的方式,使他们总给定值总结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)
 
任意给定一个大于1的整数n,设计一个算法求出n的所有因数

乳宁款项(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]

 
精彩推荐
图片推荐