雖然給魚不如教釣魚,不過思路還真不好解釋,所以附上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
: 煩請各位大大給個提示,謝謝