We don't necessarily need to recurse.(我们不一定需要递归。)
We can iterate on the known remainders so far.(到目前为止,我们可以迭代已知的余数。)
JavaScript code below (this is exhaustive; we could have a more space efficient version to return just one subset by adjusting what we store):(下面的JavaScript代码(这是详尽无遗的;我们可以有一个空间效率更高的版本,通过调整存储的内容仅返回一个子集):)
// 'rem' stands for "remainder" function f(A){ let N = A.length let rems = {0: [[]]} for (let a of A){ let newRems = {} for (let rem in rems){ let newRem = (a + Number(rem)) % N newRems[newRem] = (rems[newRem] || []).concat( rems[rem].map(x => x.concat(a))) } newRems[a % N] = (rems[a % N] || []).concat([[a]]) rems = Object.assign(rems, newRems) } return rems[0].slice(1) } var A = [1, 6, 2, 3, 4] console.log(JSON.stringify(A)) console.log(`N: ${A.length}`) console.log(JSON.stringify(f(A)))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…