1. 程式人生 > >【Leetcode_總結】970. 強整數 - python

【Leetcode_總結】970. 強整數 - python

Q:

給定兩個非負整數 x 和 y,如果某一整數等於 x^i + y^j,其中整數 i >= 0 且 j >= 0,那麼我們認為該整數是一個強整數

返回值小於或等於 bound 的所有強整數組成的列表。

你可以按任何順序返回答案。在你的回答中,每個值最多出現一次。

 

示例 1:

輸入:x = 2, y = 3, bound = 10
輸出:[2,3,4,5,7,9,10]
解釋: 
2 = 2^0 + 3^0
3 = 2^1 + 3^0
4 = 2^0 + 3^1
5 = 2^1 + 3^1
7 = 2^2 + 3^1
9 = 2^3 + 3^0
10 = 2^0 + 3^2

示例 2:

輸入:x = 3, y = 5, bound = 15
輸出:[2,4,6,8,10,14]

連結:https://leetcode-cn.com/submissions/detail/11411325/

思路:暴力求解

程式碼:

class Solution:
    def powerfulIntegers(self, x, y, bound):
        """
        :type x: int
        :type y: int
        :type bound: int
        :rtype: List[int]
        """
        res = []
        min_ = min(x, y)
        power_range = 0
        for i in range(bound):
            power_range = i
            if min_ ** power_range >= bound:
                break
        for i in range(power_range):
            for j in range(power_range):
                if x ** i + y ** j <= bound:
                    if (x ** i + y ** j) not in res:
                        res.append( x ** i + y ** j)
        return (res)