给定两个整数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 coloumn as 1 are,
{{1, 1}, {1, 1}} and {{-1, -1}, {-1, -1}}
Possible ways to get product of each row and coloumn 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
32
时间复杂度: O(log(N * M))
辅助空间: O(1)