给定两个整数N和M ,任务是找到形成大小为N * M的矩阵的方法数,该矩阵仅由 1 或 -1 组成,使得每行和每列中整数的乘积等于 1 或-1.
例子:
Input: N = 2, M = 2
Output: 4
Explanation:
Possible ways to get product of each row and column as 1 are,
{{1, 1}, {1, 1}} and {{-1, -1}, {-1, -1}}
Possible ways to get product of each row and column as -1 are,
{{1, -1}, {-1, 1}} and {{-1, 1}, {1, -1}}
Hence, number of ways = 2 + 2 = 4
Input: N = 3, M = 3
Output: 32
Explanation:
There are 16 ways to get product as 1 and 16 ways to get product as -1.
Hence, number of ways = 16 + 16 = 32
天真的方法:
解决这个问题的最简单方法是生成大小为N * M 的所有可能矩阵,并为每个矩阵计算所有行和列的乘积并检查它是 1 还是 -1。
时间复杂度: O(2 N*M )
辅助空间: O(M*N)
有效的方法:
假设前N-1行和前M-1列由 1 或 -1 填充。现在,每行最多N-1行和每列最多M-1列的乘积将是1或-1 。总共有2 (N-1) * (M-1)种方式可以组成一个大小为(N-1)*(M-1)的矩阵,填充 1 或 -1。根据需要作为 N 行和 M 列的乘积,可以相应地填充最后一行和最后一列。
请按照以下步骤解决问题:
- 如果N + M是偶数,
获得乘积的可能矩阵数为 1 = 2 (N-1) * (M-1)
获得乘积的可能矩阵数为 -1 = 2 (N-1) * (M-1) - 如果N + M是奇数,
获得乘积的可能矩阵数为 1 = 2 (N-1) * (M-1)
获得乘积为 -1 = 0 的可能矩阵数
下面是上述方法的实现:
C++
// C++ implementation of
// the above approach
#include
using namespace std;
// Function to return the
// number of possible ways
void Solve(int N, int M)
{
int temp = (N - 1) * (M - 1);
int ans = pow(2, temp);
// Check if product can be -1
if ((N + M) % 2 != 0)
cout << ans;
else
cout << 2 * ans;
cout << endl;
}
// Driver Code
int main()
{
int N = 3;
int M = 3;
Solve(N, M);
return 0;
}
Java
// Java implementation of the above approach
import java.util.Arrays;
class GFG{
// Function to return the
// number of possible ways
static void Solve(int N, int M)
{
int temp = (N - 1) * (M - 1);
int ans = (int)(Math.pow(2, temp));
// Check if product can be -1
if ((N + M) % 2 != 0)
System.out.print(ans);
else
System.out.print(2 * ans);
}
// Driver code
public static void main (String[] args)
{
int N = 3;
int M = 3;
Solve(N, M);
}
}
// This code is contributed by Shubham Prakash
Python3
# Python3 program to implement
# the above approach
# Function to return
# possible number of ways
def Solve(N, M):
temp = (N - 1) * (M - 1)
ans = pow(2, temp)
# Check if product can be -1
if ((N + M) % 2 != 0):
print(ans)
else:
print(2 * ans)
# driver code
if __name__ == '__main__':
N, M = 3, 3
Solve(N, M)
# This code is contributed by Sri_srajit
C#
// C# implementation of the above approach
using System;
class GFG{
// Function to return the
// number of possible ways
static void Solve(int N, int M)
{
int temp = (N - 1) * (M - 1);
int ans = (int)(Math.Pow(2, temp));
// Check if product can be -1
if ((N + M) % 2 != 0)
Console.Write(ans);
else
Console.Write(2 * ans);
}
// Driver Code
public static void Main(string[] args)
{
int N = 3;
int M = 3;
Solve(N, M);
}
}
// This code is contributed by rutvik_56
Javascript
32
时间复杂度: O(log(N*M))
辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live