看板 java 關於我們 聯絡資訊
雖然給魚不如教釣魚,不過思路還真不好解釋,所以附上source code 想法很簡單 把所有可能都跑過就行了 用recursive是因為比較好處理多重條件(這次取1個或者取2個) private void splitNumber(String remain, String handled) { if (remain.length() == 0) System.out.println(handled.substring(0, handled.length() -2)); } else if (remain.length() == 1) { System.out.println(handled + remain); } else { // s.lenght() >= 2 splitNumber(remain.substring(1), handled + remain.substring(0, 1) + ", "); splitNumber(remain.substring(2), handled + remain.substring(0, 2) + ", "); } } 使用function: splitNumber("1234567", ""); 結果: 1, 2, 3, 4, 5, 6, 7 1, 2, 3, 4, 5, 67 1, 2, 3, 4, 56, 7 1, 2, 3, 45, 6, 7 1, 2, 3, 45, 67 1, 2, 34, 5, 6, 7 1, 2, 34, 5, 67 1, 2, 34, 56, 7 1, 23, 4, 5, 6, 7 1, 23, 4, 5, 67 1, 23, 4, 56, 7 1, 23, 45, 6, 7 1, 23, 45, 67 12, 3, 4, 5, 6, 7 12, 3, 4, 5, 67 12, 3, 4, 56, 7 12, 3, 45, 6, 7 12, 3, 45, 67 12, 34, 5, 6, 7 12, 34, 5, 67 12, 34, 56, 7 ※ 引述《OoShiunoO (機機勳)》之銘言: : 請問各位大大 : 如果我有一個數字, ex: 213112 : 我要怎麼把它拆成各種組合呢?(題目是限定最大只能拆成10位數) : 2,1,3,1,1,2 : 21,3,1,1,2 : 2,13,1,1,2 : . : . : . : . : 21,31,12 : 煩請各位大大給個提示,謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 219.87.150.73 ※ 文章網址: https://www.ptt.cc/bbs/java/M.1428992992.A.957.html
cha122977: 對了 這個做法其實是divide and conquer 可以wiki一下 04/14 14:33
jjmachen: 原PO的10位數,原來是指不超過99的數字,還以為是10個位數 04/14 21:54
omie: 10位數跟2位數搞不清楚.... 04/15 01:21
cha122977: 我是看例子推敲的…不過10位的話做法也是類似 04/15 17:03
omie: 我說的是原po把2位數當成10位數 04/15 22:39
jej: 用ABC 分成 A B C, AB C, A BC 寫成基本method, 接下來遞迴 04/23 12:33
jej: 中間判斷 A或是 B或是C 或是AB 或是BC 超過十位則略過 04/23 12:34
cha122977: 樓上這種做法中 ABCD中的BC會被算到兩次(A BC 和 BC D) 04/24 18:18