题干:一个人一次可以吃1颗糖,也可以吃2颗糖,也可以同时吃下n颗糖。求这个人吃完n颗糖有多少种方式。
function findWayEatSugarNumber(n) { const wayArr = findWayEatSugar(n); const returnArr = wayArr.map((ele) => ele.sort()).map((ele) => ele.join()); return Array.from(new Set(returnArr)); } function findWayEatSugar(n) { const result = [[n]]; for (let i = 1; i <= n; i++) { const j = n - i; if (j === 0) continue; const jArr = findWayEatSugar(j); const prevArr = jArr.map((ele) => [i, ...ele]); result.push(...prevArr); } return result; } const testArr = [1, 2, 3, 4, 5, 6, 7, 8]; testArr.forEach((ele) => { const result = findWayEatSugarNumber(ele); console.log(`吃${ele}颗糖,共有${result.length}种方式,分别为:`, result); })
标签:...,findWayEatSugar,const,wayArr,ele,问题,算法,result,吃糖 From: https://www.cnblogs.com/LeoXnote/p/17823571.html