Problem
Numbers can be regarded as product of its factors. For example,
8 = 2 x 2 x 2;
= 2 x 4.
Write a function that takes an integer n and return all possible combinations of its factors.
Note:
You may assume that n is always positive.
Factors should be greater than 1 and less than n.
Example 1:
Input: 1 Output: []
Example 2:
Input: 37 Output:[]
Example 3:
Input: 12 Output: [ [2, 6], [2, 2, 3], [3, 4] ]
Example 4:
Input: 32 Output: [ [2, 16], [2, 2, 8], [2, 2, 2, 4], [2, 2, 2, 2, 2], [2, 4, 4], [4, 8] ]Solution
class Solution { public List> getFactors(int n) { List
> res = new ArrayList<>(); if (n == 1) return res; helper(n, 2, new ArrayList<>(), res); return res; } private void helper(int n, int factor, List
temp, List > res) { if (n == 1 && temp.size() > 1) { res.add(new ArrayList<>(temp)); } //i starts from factor, to ensure that all factors equals or larger than 2 for (int i = factor; i <= n; i++) { if (n%i == 0) { temp.add(i); helper(n/i, i, temp, res); temp.remove(temp.size()-1); } } } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/72247.html
找出string里的單詞。 186. Reverse Words in a String II, 434. Number of Segments in a String combination類型題 77. Combinations 39. Combination Sum 40. Combination Sum II 216. Combination Sum III 494. Target S...
摘要:用的思想,加上題目的特殊意思,來解決問題。如果個數(shù)字,有種結(jié)果。這里對原題多加了一個輸出的要求,代碼如下。也是為了去重,兩個分解的解法是對稱的,乘法對稱的重點(diǎn)就是 用combination的思想,加上題目的特殊意思,來解決問題。 526 Beautiful Arrangement Suppose you have N integers from 1 to N. We define a ...
摘要:題目描述題目理解將一段字符廣度搜索截取,分別有種組合形式,添加限制條件,過濾掉不適合的組合元素。長度,大小,首字母應(yīng)用如果進(jìn)行字符串的子元素組合窮舉,可以應(yīng)用。所有的循環(huán),利用到前一個狀態(tài),都可以理解為動態(tài)規(guī)劃的一種分支 題目描述:Given a string containing only digits, restore it by returning all possible va...
摘要:本題與類似,都是用回溯法。求中個數(shù)的不同組合,很明顯我們需要注意的就是每個數(shù)字只能出現(xiàn)一次,這點(diǎn)與不同。 CombinationsGiven two integers n and k, return all possible combinations of k numbers out of 1 ... n. For example, If n = 4 and k = 2, a solu...
摘要:最新更新請見深度優(yōu)先搜索復(fù)雜度時間空間遞歸棧空間思路首先建一個表,來映射號碼和字母的關(guān)系。然后對號碼進(jìn)行深度優(yōu)先搜索,對于每一位,從表中找出數(shù)字對應(yīng)的字母,這些字母就是本輪搜索的幾種可能。 Letter Combinations of a Phone Number 最新更新請見:https://yanjia.me/zh/2019/01/... Given a digit string...
閱讀 1536·2023-04-26 02:08
閱讀 3128·2021-10-14 09:42
閱讀 7177·2021-09-22 15:34
閱讀 3236·2019-08-30 13:16
閱讀 2719·2019-08-26 13:49
閱讀 1342·2019-08-26 11:59
閱讀 1251·2019-08-26 10:31
閱讀 2170·2019-08-23 17:19