https://leetcode.com/problems/find-unique-binary-string/description
每次看到位元操作都會直覺想到 XOR,但這題沒有,直接枚舉並檢查就好了:
from typing import List
class Solution:
def findDifferentBinaryString(self, nums: List[str]) -> str:
n = len(nums[0])
dict = {}
for num in nums:
dict[int(num, 2)] = True
for num in range(pow(2, n)):
if dict.get(num) == None:
return f"{num:0{n}b}"
return ""但還可以更好,如果腦袋想到 dict = True or False,都應該要換成 Set 才對。再來,根據鴿籠原理(Pigeonhole Principle),我們最多只會需要遍歷 n+1 次就可以找到答案了。
from typing import List
class Solution:
# len(nums) is expected to be equal to len(nums[i])
def findDifferentBinaryString(self, nums: List[str]) -> str:
n = len(nums)
set = ()
seen = [int(num, 2) for num in nums]
# Base on Pigeonhole Principle, we only have to
# enumerate until len(nums)+1 instead of limit(n)+1
for num in range(n + 1):
if num not in seen:
return f"{num:0{n}b}"
return ""咦?我 2025-02-20 有解過?
#include <algorithm>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
class Solution {
public:
std::string findDifferentBinaryString(std::vector<std::string> &nums) {
int n = nums.size();
std::string result;
for (int i = 0; i < n; i++) {
result += nums[i][i] == '0' ? '1' : '0';
}
return result;
}
};窩靠 … 只要每個列都挑一個不一樣的位元,那最後組合起來的就必是之前沒有的組合!
我那時怕不是個天才!