Noo*_*les 2 algorithm search combinations
假如你有字符串:1234
我需要的是从这个字符串生成所有可能的数字组合,但必须保持字符串的原始顺序.
每个结果中必须至少有2个数字.
在1234的情况下,输出将是列表的列表
输出清单:
list: 1, 2, 3, 4
list: 12, 3, 4
list: 123, 4 --Note a list containing only 1234 is not valid
list: 1, 23, 4
list: 1, 234
list: 1, 2, 34
list: 12, 34
Run Code Online (Sandbox Code Playgroud)
另请注意,每个结果列表中的数字始终与原始字符串1234的顺序相同.因此,组合34,21或213,4的列表无效.
我能想到的唯一方法:
然而,根据我的方法,我不知道如何生成12,34组合
任何帮助是极大的赞赏!
1 | 2 | 3 | 4 | 5
| | | |
d1 d2 d3 d4
Run Code Online (Sandbox Code Playgroud)
假设原始字符串的长度为5,我们通过添加一个可以为空的分隔符d1,d2,d3和d4来划分该字符串.
12345.1, 23451,2,3,4,5对于我们添加的每个分隔符,它有两个选项:可见或消失,因此总可能的数量是2^(n-1) - 1当n是原始字符串的长度时
然后,我们将解决的下一个问题是迭代所有可能性:使用二进制值来表示分隔符:
for (int i = 1; i <= pow(2, n - 1); i++) {
// i = 1, 0b0001, d4 is visible, we get 1234,5
// i = 2, 0b0010, d3 is visible, we get 123,45
// i = 3, 0b0011, d3 and d4 is visible, we get 123,4,5
// i = 4, 0b0100, d2 is visible, we get 12,345
// i = 5, 0b0101, d2 and d4 is visible, we get 12, 34, 5
// i = 6, 0b0110, d2 and d3 is visible, we get 12, 3, 45
// i = 7, 0b0111, d2,d3,d4 is visible, we get 12,3,4,5
// go on...
}
Run Code Online (Sandbox Code Playgroud)
希望有帮助......
| 归档时间: |
|
| 查看次数: |
270 次 |
| 最近记录: |