LeetCode #254 Factor Combinations 因子的組合 254 Factor Combinations 因子的組合

254 Factor Combinations 因子的組合

Description:

Numbers can be regarded as the product of their factors.

For example, 8 = 2 x 2 x 2 = 2 x 4.
Given an integer n, return all possible combinations of its factors. You may return the answer in any order.

Note that the factors should be in the range [2, n - 1].

Example:

Example 1:

Input: n = 1
Output: []

Example 2:

Input: n = 12
Output: [[2,6],[3,4],[2,2,3]]

Example 3:

Input: n = 37
Output: []

Constraints:

1 <= n <= 10^7

題目描述:

整數可以被看作是其因子的乘積。

例如:

8 = 2 x 2 x 2;
= 2 x 4.
請實現一個函數,該函數接收一個整數 n 並返回該整數所有的因子組合。

注意:

你可以假定 n 爲永遠爲正數。
因子必須大於 1 並且小於 n。

示例:

示例 1:

輸入: 1
輸出: []

示例 2:

輸入: 37
輸出: []

示例 3:

輸入: 12
輸出:
[
[2, 6],
[2, 2, 3],
[3, 4]
]

示例 4:

輸入: 32
輸出:
[
[2, 16],
[2, 2, 8],
[2, 2, 2, 4],
[2, 2, 2, 2, 2],
[2, 4, 4],
[4, 8]
]

思路:

回溯
i 從 2 開始遍歷直到 i * i > n
當 n 能整除 i 時, 以 { i, n / i } 爲起始數組進行回溯
回溯時每次從倒數第二的數開始, 這個數也是當前數組第二大的數直到 i * i > 最後一個數
每次遍歷到最後一個數能整除 i, 去掉最後一個數並加入 i 和 最後一個數除 i 的商
時間複雜度爲 O(nlgn), 空間複雜度爲 O(lgn)

代碼:

C++:

class Solution 
{
    vector<vector<int>> result;
    void dfs(vector<int>&& start)
    {
        result.emplace_back(start);
        for (int i = *++rbegin(start); i * i <= start.back(); i++)
        {
            if (!(start.back() % i))
            {
                vector<int> cur(start.begin(), start.end() - 1);
                cur.emplace_back(i);
                cur.emplace_back(start.back() / i);
                dfs(move(cur));
            }
        }
    }
public:
    vector<vector<int>> getFactors(int n) 
    {
        for (int i = 2; i * i <= n; i++) if (!(n % i)) dfs({i, n / i});
        return result;
    }
};

Java:

class Solution {
    private List<List<Integer>> result = new ArrayList<>();
    
    public List<List<Integer>> getFactors(int n) {
        dfs(n, new ArrayList<>());
        return result;
    }
    
    private void dfs(int n, List<Integer> cur) {
        if (n == 1) if (cur.size() > 0) result.add(new ArrayList<>(cur));
        if (n == 1) return;
        for (int i = cur.isEmpty() ? 2 : cur.get(cur.size() - 1); i * i <= n; i++) {
            if (n % i == 0) {
                cur.add(i);
                cur.add(n / i);
                result.add(new ArrayList<Integer>(cur));
                cur.remove(cur.size() - 1);
                dfs(n / i, cur);
                cur.remove(cur.size() - 1);
            }
        }
    }
}

Python:

class Solution:
    def getFactors(self, n: int) -> List[List[int]]:
        def dfs(n: int, r: int) -> List[List[int]]:
            result = []
            for i in range(r, int(sqrt(n)) + 1):
                if not n % i:
                    result.append([i, n // i])
                    for sub in dfs(n // i, i):
                        result.append(sub + [i])
            return result
        return dfs(n, 2)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章