正整数n的有序m拆分-实现方法

需求:输入一个正整数n,拆分成m份有多少种情况,输出,不同的顺序算不同的情况,即有序
实现方法:

// solve函数用来输入n,m 输出n的m拆分情况数组
var solve = n => callback => {
    let rest = n;       // the rest number to fill
    let working = [];   // the working array
    let i = 0;          // the current index of working array
    let mrf = -1;       // the most recently filled number
  
    while (true) {
      if (rest == 0) {
        callback(working.slice(0));
        if (i >= n) return;
        while (true) {
          --working[--i];
          ++rest;
          if (working[i] == 0) {
            working.splice(i);
          } else {
            mrf = working[i++];
            break;
          }
        }
      } else {
        let value = (i == 0 || rest < mrf) ? rest : mrf;
        mrf = working[i++] = value;
        rest -= value;
      }
    };
  };
// 输入:数组
// 输出:数组的全排序
  function permute(input) {
    var permArr = [],
    usedChars = [];
    function main(input){
      var i, ch;
      for (i = 0; i < input.length; i++) {
        ch = input.splice(i, 1)[0];
        usedChars.push(ch);
        if (input.length == 0) {
          permArr.push(usedChars.slice());
        }
        main(input);
        input.splice(i, 0, ch);
        usedChars.pop();
      }
      return permArr
    }
    return main(input);
  };
function diffPush(father, uncle) {
    console.log('middle', father, uncle);
    let compare = true;
    for(let cousin of uncle) {
        compare = true;
        for(let baby of father) {
            if(baby.toString() == cousin.toString()) {
                compare = false;
                break;
            }
        }
        compare && father.push(cousin);
    }   
    // return father;
}
  // 输入:7,3
  // 输出: 7份成3份的有序拆分二维数组
function part(n, m) {
    var all = [];
    solve(n)(a => {
        if(a.length == m){
            // all.push(...permute(a));
            diffPush(all, permute(a));
        }
    });
    console.log('有序拆分结果--', all, '--有序拆分结果');
    return all;
}

运行结果:


有序拆分-算法结果.png

你可能感兴趣的:(正整数n的有序m拆分-实现方法)