[英]All possible combinations of an array without repeating?
Say I have and array: 说我有和数组:
var arr = [1,2,3,4];
How would I go about getting all possible combinations without repeating? 我将如何重复获取所有可能的组合?
For instance: 例如:
// "2,1" wouldn't be valid because it's essentially "1,2"
1
1,2
1,2,3
1,2,3,4
2
2,3
2,3,4
3
3,4
4
What you want aren't all possible combinations ( subsets , missing are 1,3
, 1,4
, 2,4
), but all subsequences . 你想是不是所有可能的组合是什么( 子集 ,失踪是
1,3
, 1,4
, 2,4
),但所有的子序列 。 You can get those easily by using two nested loops for start and end of the sequence: 您可以使用两个嵌套循环作为序列的开始和结束来轻松获得这些信息:
function subsequences(arr) {
var res = [[]];
for (var i=0; i<arr.length; i++)
for (var j=i+1; j<=arr.length; j++)
res.push(arr.slice(i, j));
return res;
}
For all possible subsets - the power set - see this answer . 对于所有可能的子集- 功率集 -请参见此答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.