我試圖解決在本文給出了這個問題https://leetcode.com/problems/factor-combinations/description/如何找到dfs +回溯算法的時間複雜度?
數字可以被看作是其因素的產物。例如
8 = 2 x 2 x 2; = 2 x 4.
編寫一個採用整數n並返回所有可能的因子組合的函數。
儘管我能夠使用dfs方法編寫代碼,但我很難在輸入方面驅動其最壞情況時間複雜性。任何人都可以幫忙嗎?
public List<List<Integer>> getFactors(int n) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> current = new ArrayList<Integer>();
getFactorsHelper(n,2,current,result);
return result;
}
public void getFactorsHelper(int n,int start,List<Integer> current, List<List<Integer>> result){
if(n<=1 && current.size()>1){
result.add(new ArrayList<>(current));
return;
}
for(int i=start;i<=n;i++){
if(n%i==0) {
current.add(i);
getFactorsHelper(n/i,i,current,result);
current.remove(current.size()-1);
}
}
}
時間複雜度就什麼變化? –
關於輸入n – KBR
好的,但請記住,它將大幅波動 - 例如127只有一個輸出,而128有負載。 –