找出两个整数的所有可能组合



每次我可以爬1到2级台阶到达顶部(例如3级)1 + 1 + 1 1 + 2 2 + 1。有三种情况(场景)。这是我的巫毒代码(一些数字(缺失)在n = 5时没有出现,它是1211。解决方案是使用相反的字符串,并在哈希中存储两个版本的字符串,这样重复的字符串就会消失,并在循环后对它们求和。

function setCharAt(str, index, chr) {
if (index > str.length - 1) return str;
return str.substring(0, index) + chr + str.substring(index + 1);
}
let n = 9;
find(n);
function find(n) {
let origin = n; //every loop n decreases by one when it 0 while returns false,
let sum = 1;
n -= 1; //because n once once of 1's (n = 5) 1+1+1+1+1 then 1111, 1112 etc. 
if (n <= 1) return sum;
while (origin <= n * 2) { //if n = 10; only"22222" can give 10, we don't go deeper
let str = "1".repeat(n); //from "1" of n(4) to "1111"
let copyStr = str;
while (str.length === copyStr.length) { //at the end we get 2222 then 22221, 
// therefore the length will change, we exit the loop
let s = str.split('').reduce((a, b) => Number(a) + Number(b), 0); //countinng elems
console.log(str, "=", s);
if (s === origin) ++sum; //if elems equals the target we increase the amount by one
let one = str.lastIndexOf("1");
let two = str.lastIndexOf("2");
if (str[one] === "1" && str[one + 1] === "2") {
str = setCharAt(str, one, "2");
str = setCharAt(str, one + 1, "1");
} else {
str = setCharAt(str, one, "2");
}
}
--n;
}
console.log(sum)
}

如果我理解了你的问题,你想让n = 5得到1和2的所有组合(当你求和时),得到5的和(11111,1112等)?

在这种情况下,你很可能想使用递归,因为它更容易。如果你只有两个值(1和2),你可以很容易地实现这一点:
getAllCombinations = (n = 1) => {
const combinations = [];
const recursion = (n, sum = 0, str = "") => {
if (sum > n) return;
if (sum === n) {
combinations.push(str);
return;
}
// Add 1 to sum
recursion(n, sum + 1, str + "1");
// Add 2 to sum
recursion(n, sum + 2, str + "2");
};
recursion(n);
return combinations;
};

相关内容

  • 没有找到相关文章

最新更新