Swift-字符串的组合

题目:输入一个字符串,输出该字符串中字符的所有组合。举个例子,如果输入abc,它的组合有a、b、c、ab、ac、bc、abc.
在求一个字符串中所有字符的组合的时候,针对一个字符,有两种情况,假设在长度为n的字符串中选择长度为m的组合字符串,有两种选择:
①选择长度为n的字符串中的第一个字符,那么要在其余的长度n-1的字符串中选择m-1个字符
②不选择长度为n的字符串中的第一个字符,那么要在其余的长度n-1的字符串中选择m个字符
递归结束的条件就是,当m为0,即从字符串中不再选出字符的时候,这个时候已经找到了m个字符的组合,输出即可.
<pre><code>`

func stringCombination(str:String) {
    let result:[String] = []
    for i in 1...str.characters.count {
        combination(str: str, m: i, result: result)
    }

}

func combination(str:String,m:Int,result:[String]) {
    var data = result
    if m == 0 {
        print("FlyElephant--排列---\(result)")
        return
    }
    
    if str.characters.count != 0 {
        data.append(str[0]) // 保留第一个字符
        let index = str.index(str.startIndex, offsetBy: 1)
        let nextStr:String = str.substring(from: index)
        combination(str: nextStr, m: m-1, result: data) // 第一个字符与m-1个字符之间的组合
        data.remove(at: data.count-1) // 删除最后字符
        combination(str: nextStr, m: m, result: data) // 第一个字符与m个字符之间的组合
    }
}`</code></pre>

测试代码:
<pre><code>var str:String = "abc" permutation.stringCombination(str: str)</code></pre>
题目:输入一个字符串,输出该字符串中字符的所有组合。举个例子,如果输入abc,它的组合有a、b、c、ab、ac、bc、abc.
在求一个字符串中所有字符的组合的时候,针对一个字符,有两种情况,假设在长度为n的字符串中选择长度为m的组合字符串,有两种选择:
①选择长度为n的字符串中的第一个字符,那么要在其余的长度n-1的字符串中选择m-1个字符
②不选择长度为n的字符串中的第一个字符,那么要在其余的长度n-1的字符串中选择m个字符
递归结束的条件就是,当m为0,即从字符串中不再选出字符的时候,这个时候已经找到了m个字符的组合,输出即可.
<pre><code>`

func stringCombination(str:String) {
    let result:[String] = []
    for i in 1...str.characters.count {
        combination(str: str, m: i, result: result)
    }

}

func combination(str:String,m:Int,result:[String]) {
    var data = result
    if m == 0 {
        print("FlyElephant--排列---\(result)")
        return
    }
    
    if str.characters.count != 0 {
        data.append(str[0]) // 保留第一个字符
        let index = str.index(str.startIndex, offsetBy: 1)
        let nextStr:String = str.substring(from: index)
        combination(str: nextStr, m: m-1, result: data) // 第一个字符与m-1个字符之间的组合
        data.remove(at: data.count-1) // 删除最后字符
        combination(str: nextStr, m: m, result: data) // 第一个字符与m个字符之间的组合
    }
}`</code></pre>

测试代码:
<pre><code>var str:String = "abc" permutation.stringCombination(str: str)</code></pre>

FlyElephant.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容