1666. 組合+判斷素數
阿新 • • 發佈:2020-08-15
1666.組合+判斷素數
中文English
給定n
個整數和一個整數k
, 你可以從中選擇k
個整數, 現在,要求你計算出k
個數和為素數共有多少種方案。
樣例
樣例 1:
輸入:a=[3,7,12,19],k=3
輸出:1
解釋:
There are 4 ways
3+7+12=22 3+7+19=29 7+12+19=38 3+12+19=34
and only 29 is a prime.
樣例 2:
輸入:a=[1,2,3], k=2 輸出:2 解釋: There are 3 ways 1 + 2 = 3 1 + 3 = 4 2 + 3 =5 and only 3 and 5 are primes.
注意事項
n
不超過1010k
不超過n
class Solution: """ @param a: the n numbers @param k: the number of integers you can choose @return: how many ways that the sum of the k integers is a prime number """ def getWays(self, a, k): # Write your code here #首先找到所有的組合,for迴圈內嵌dfs,然後給出子函式,判斷是否是素數 results= [] self.getAllArray(results, a, [], k) count = 0 #print(results) for result in results: if self.isPrime(result): count += 1 return count #遞迴的傳參 def getAllArray(self,results, a, array, k): #遞迴的出口if (k == 0): results.append(sum(array)) #遞迴的拆解 for i in range(len(a)): self.getAllArray(results, a[i + 1: ], array + [a[i]], k - 1) def isPrime(self, num): for i in range(2, num): if num % i == 0: return False return True