[英]What is the most efficient way to generate all possible shapes formed by 10 orthogonally connected points?
[英]What is the most efficient way to generate subsets?
我想做的如下:
輸入:n,例如n = 3
輸出:{000,001,010,011,100,101,110,111},生成所有子集,我不在乎這些子集的順序
我已經實現了一種算法:
for (long i = 0, max = 1 << n; i < max; i++) {
for (int j = 0; j < n; j++) {
// check if the j bit is set to 1
int isSet = (int) i & 1 << j;
if (isSet > 0) {
// if yes, set the corresponding jth bit of x as 1.
}
}
// add x to results;
}
我知道格雷碼可以做這樣的事情。 但是我想知道哪種方法是生成子集的最有效方法?
我不確定確切的含義是“最高效”,但是如果您追求速度優化,則只能希望進行一些次要的優化,因為我懷疑您會找到更快的算法。
如果要提高速度,請嘗試一下( 如果確實可以加快代碼速度,請始終進行概要分析! ):
int
而不是long
,如果max
是足夠小,適合在一個int
。 這可能會更快。 1 << j
。 [我不確定這是否會提高速度,但是值得嘗試] 您還應該更換
int isSet = (int) i & 1 << j;
if (isSet > 0) {
// if yes, set the corresponding jth bit of x as 1.
}
通過:
if (0!=(int) i & 1 << j) {
// if yes, set the corresponding jth bit of x as 1.
}
除非您需要在其他地方再次使用變量isSet
。
關於格雷碼:這將最大程度地減少位更改的數量,但是我看不到如何改善所有子集的生成,但是格雷碼很有用,如果您對具有以下特征的子集順序感興趣:遍歷它們時僅在一個元素上有所不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.