如何从列表的给定范围内生成所有可能的列表,这些范围将以给定的输入总和为目标

时间:2019-07-12 11:53:38

标签: python python-3.x list

输入:目标总和

输出:列表[1,2,3]中具有给定总和的所有可能排列的计数

示例输入:4和相应的输出:7

所有可能的对:

1, 1, 1, 1
1, 2, 1
1, 1, 2   
1, 3    
2, 1, 1    
2, 2    
3, 1

对于这些给定的排列以解释输出,所有这些都必须取自[1,2,3]对于任何输入。

这是我到目前为止尝试过的:

def combinationSum(self, candidates, target):

    rests = [[] for _ in range(target)]
    for num in candidates:
        if num > target:
            continue
        else:
            rests[target - num].append([num])
        for cur_rest in range(target - 1, num - 1, -1):
            for result in rests[cur_rest]:
                rests[cur_rest - num].append(result + [num])

    return rests[0]

s=Solution()
c=[1,2,3]
t=int(input())
print(s.combinationSum(c,t))

1 个答案:

答案 0 :(得分:0)

根据@Tomerikoo建议的解决方案,我创建了具有一些修改的解决方案。

it(`should generate the stream correctly`, () => {
    ts.run(({ hot, expectObservable }) => {

      const marbles = [
        '-a-----', // obs2 marble
        '100ms x', // expected marble
      ]

      const [obs2Marble, expectedMarble] = marbles

      const obs2EventsMap = {...}

      const expectedMap = {...}

      const mockInput = hot(obs2Marble, obs2EventsMap)

      const obs1$ = require('./obs1').default
      expectObservable(obs1$).toBe(expectedMarble, expectedMap)
    })
  })

希望得到帮助!

相关问题