LintCode 652: Factorization (DFS 搜索經典題)

  1. Factorization
    中文English
    A non-negative numbers can be regarded as product of its factors.
    Write a function that takes an integer n and return all possible combinations of its factors.

Example
Example1

Input: 8
Output: [[2,2,2],[2,4]]
Explanation:
8 = 2 x 2 x 2 = 2 x 4
Example2

Input: 1
Output: []
Notice
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combination.

解法1:DFS搜索。
思路:這題與subset有點相似,
注意:

  1. 在helper裏面,要判斷v.size()>0,不然就會把空集加進去。
  2. for()裏面,上限是sqrt(n)。
  3. helper()裏面,if()裏面push_back(v)之後,千萬不能返回,這裏跟subset不一樣。
  4. 不需要sort。
    舉例如下:
    input = 12。
    一開始i = 2, 將2存入v,遞歸後helper(6, 2, v, vv),將{2,6}存入vv,v彈出6。繼續for循環,將另一個2存入v,遞歸helper(3, 2, v, vv),將{2,2,3}存入vv,彈出3。後面以2開始的for循環再不滿足條件了。將2逐個從v中彈出。
    i=3的時候,將3存入v,遞歸後helper(4,3,v,vv),將{3,4}存入vv, v彈出4。繼續for循環,後面都不滿足條件了。
    所以返回{{2,6}, {2,2,3}, {3, 4}}。
    注意這裏helper()裏面if()裏千萬不能返回。這樣,6還可以繼續處理成{2,3}。

代碼如下:

class Solution {
public:
    /**
     * @param n: An integer
     * @return: a list of combination
     */
    vector<vector<int>> getFactors(int n) {
        vector<int> v;
        vector<vector<int>> vv;
        helper(n, 2, v, vv);
        return vv;
    }

private:
    void helper(int n, int index, vector<int> & v, vector<vector<int>> &vv) {
        if (v.size() > 0) {
            v.push_back(n);
            vv.push_back(v);
            v.pop_back();
        }
        for (int i = index; i <= sqrt(n); ++i) {
            if (n % i == 0) {
                v.push_back(i);
                helper(n / i, i, v, vv);
                v.pop_back();
            }
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章