简体   繁体   中英

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 . 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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