好了,如果你有這樣的數字(任意大小)的列表(從列表號)和(簡單的數學運算符)的所有組合:如何獲得
[5, 7] (It's short so i can type all the combinations)
我要像一個循環返回這樣的組合的列表:
5+7
5-7
5*7
5/7
7+5
7-5
7*5
7/5
我曾想過這一段時間,我知道它的結構採用樹形圖,但我只是不知道如何使它列表的任何大小工作。
好了,如果你有這樣的數字(任意大小)的列表(從列表號)和(簡單的數學運算符)的所有組合:如何獲得
[5, 7] (It's short so i can type all the combinations)
我要像一個循環返回這樣的組合的列表:
5+7
5-7
5*7
5/7
7+5
7-5
7*5
7/5
我曾想過這一段時間,我知道它的結構採用樹形圖,但我只是不知道如何使它列表的任何大小工作。
最簡單的方法是使用遞歸算法,如:
combination(list)
for(numbers,operators)
combination_list+=number+operation+combination(rest)
return combination_list
您可以通過使用迭代的方法做它,以及任何遞歸算法具有迭代對應
的一般解
void operations(int[] numbers){
int size = //determine the number of elements in the array
for(int i=0; i < size; i++){
for (int j = 0; j < size;j++){
if(i !=j){
/*do all the operations
numbers[i] + numbers[j]
numbers[i] - numbers[j]
numbers[i] * numbers[j]
numbers[i]/numbers[j]
*/
}
}
}
}
有關這第一個背後的組合: 生成整數列表的所有可能的排序將是N!組合和每個組合上,然後在它們之間的所有可能的運算符選擇[運算符數目]^[整數間的間隔數目],所以4 ^(n-1) 將這兩個數字相乘得到總數您將擁有的房源數量:N!*(4 ^(n-1))
只需在列表中添加第三個整數就可以得到96種可能的組合,而第四種則可以獲得1536個,我相信您知道盡管這將會非常迅速地增長。
(和我也忽略了一個事實,如果你的清單中有重複的整數你不需要創建列表的重複排列,因此,所有上述的只適用於獨特的整數列表)
我想我會嘗試這樣做的方式是首先創建N個整數的所有排列的列表,並單獨列出所有N-1多個運算符的選擇。然後使用一對foreach循環將它們組合成一個更大的列表。
List<Integer[]> orderings = //a bunch of arrays each one being a unique ordering of all integers in the inital listing
List<Character[]> selections = //a bunch of arrays each one being a unique selection of the 4 operators
List<String> combinations = new ArrayList<String>();
for(Integer[] order : orderings) {
for(Character[] selection : selections) {
//now combine order (numbers) and selection(operators) alternating between indexes
String combination = order[0].toString();
for(int i = 0; i < selection.length; i++) {
combination += selection[i].toString() + order[i+1].toString();
}
combinations.add(combination);
}
}
生成數字的排列就像尋找所有可能的排序爲一副牌,那就是應該有其他地方在堆棧溢出許多很容易找到,能解決的問題,並找到運營商的所有選擇也不是很難。
編輯:哦,我只是意識到,我不知道如果你是特別想要唯一的數字對,所以3個數字列表將只輸出任何兩個整數的配對,而不是包含所有3的排序,如果它是隻需要一對數字,問題就會變得簡單一些。
定義「所有組合」對於兩個以上的元素實際上意味着什麼。如果說,我們有''[1,2,3]''什麼是期望的輸出?例如。 「1 + 2 + 3」,「(1 + 2)+ 3」和「1+(2 + 3)」都是等價的,但是以不同的方式寫入。這些算作1嗎?如果是這樣,你想製作哪些? – zegkljan