给定一个整数N ,任务是打印由N的二进制表示形式中存在的置位位形成的该组的所有子集。
例子:
Input: N = 5
Output: 5 4 1
Explanation:
Binary representation of N is “101”, Therefore all the required subsets are {“101”, “100”, “001”, “000”}.
Input: N = 25
Output: 25 24 17 16 9 8 1
Explanation:
Binary representation of N is “1101”. Therefore, all the required subsets are {“11001”, “11000”, “10001”, “10000”, “01001”, “01000”, “0001”, “0000”}.
天真的方法:最简单的方法是遍历[0,1 <<((N中的设置位的数量) ]范围内的每个掩码,并检查是否除N中的位之外未设置其他位。然后打印。
时间复杂度: O(2 (N中的设置位数) )
辅助空间: O(1)
高效方法:上述方法可以仅通过遍历它们的掩模n中的子集中的submasks进行优化。
- Suppose S is the current submask which is the subset of mask N. Then, it can be observed that by assigning S = (S – 1) & N, the next submask of N can be obtained which is less than S.
- In S – 1, it flips all the bits present on the right of the rightmost set bit including rightmost set bit of S.
- Therefore, after performing Bitwise & with N, a submask of N is obtained.
- Therefore, S = (S – 1) & N gives the next submask of N which is less than S.
请按照以下步骤解决问题:
- 初始化变量,例如S =N。
- 在S> 0时进行迭代,并在每次迭代中打印S的值。
- 分配S =(S – 1)&N。
下面是上述方法的实现:
C++
// C++ Program for above approach
#include
using namespace std;
// Function to print the submasks of N
void SubMasks(int N)
{
for (int S = N; S; S = (S - 1) & N) {
cout << S << " ";
}
}
// Driver Code
int main()
{
int N = 25;
SubMasks(N);
return 0;
}
Java
// Java Program for above approach
import java.util.*;
class GFG
{
// Function to print the submasks of N
static void SubMasks(int N)
{
for (int S = N; S > 0; S = (S - 1) & N)
{
System.out.print(S + " ");
}
}
// Driver Code
public static void main(String args[])
{
int N = 25;
SubMasks(N);
}
}
// This code is contributed by SURENDRA_GANGWAR.
Python3
# Python3 program for the above approach
# Function to print the submasks of N
def SubMasks(N) :
S = N
while S > 0:
print(S,end=' ')
S = (S - 1) & N
# Driven Code
if __name__ == '__main__':
N = 25
SubMasks(N)
# This code is contributed by bgangwar59.
C#
// C# program for the above approach
using System;
class GFG{
// Function to print the submasks of N
static void SubMasks(int N)
{
for (int S = N; S > 0; S = (S - 1) & N)
{
Console.Write(S + " ");
}
}
// Driver Code
static public void Main()
{
int N = 25;
SubMasks(N);
}
}
// This code is contributed by Code_hunt.
Javascript
输出:
25 24 17 16 9 8 1
时间复杂度: O(2 (N中的设置位数) )
辅助空间: O(1)