繁体   English   中英

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

[英]find all possible combinations of two integers

每次我可以爬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;

};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM