这是我到目前为止所提出的(它基本上生成分区就好像它是笛卡尔积):
function partitions(str) {
/**
* @example
* partitions('abc') // ["abc", "ab-c", "a-bc", "a-b-c"]
*
*/
const result = [];
const sets = str.split('').map(x => [x, x + '-']);
const max = sets.length - 1;
// in this example: ['c', 'c-'] -> ['c'] (because it's the last character)
sets[max].pop();
function helper(arr, i) {
for (let j = 0; j < sets[i].length; j++) {
const c = arr.slice(0); // clone arr
c.push(sets[i][j]);
if (i === max) result.push(c.join('')); else helper(c, i + 1);
}
}
helper([], 0);
return result;
}
实现此类功能的正确方法是什么?