在数组中查找组合
我在java中有这样的2D数组
transmission communication tv television approach memorycode methodact
我需要得到所有组合,如:
{transmission,approach,methodact},{transmission,memorycode,methodact},{communication,approach,methodact},...
有人可以提供一个适用于nXn数组的例子,即使它只有两行吗?
这应该是诀窍:
static Set> allComb(String[][] opts) { Set> results = new HashSet>(); if (opts.length == 1) { for (String s : opts[0]) results.add(new ArrayList (Arrays.asList(s))); } else for (String str : opts[0]) { String[][] tail = Arrays.copyOfRange(opts, 1, opts.length); for (List combs : allComb(tail)) { combs.add(str); results.add(combs); } } return results; }
JavaScript中的此代码可以帮助您:
var sampleArray = [[“transmission”,“communication”,“tv”,“television”],[“approach”,“memorycode”],[“methodact”]];
var GetAllCombinations = function(array2d){
var ret=[]; var fn = function(arr,index,cur) { var ret = []; for (var i=0; i
} console.log(GetAllCombinations(sampleArray));
它构建从给定数组开始的所有组合,迭代该级别的所有选项并递归调用它,然后将其与结果连接。