全排列

作者: Isy | 来源:发表于2016-08-01 19:56 被阅读24次

全排列

#import <Foundation/Foundation.h>

@interface Permutation : NSObject
- (void)permutation:(NSString*)str;
@end

#import "Permutation.h"

@implementation Permutation
static int i = 0;
- (void)perm:(NSMutableString*)sofar andRest:(NSMutableString*)rest{
    for (int i  = 0; i < (int)rest.length; i++) {
        NSMutableString *next = [NSMutableString stringWithString:sofar];
        NSMutableString *remaing = [NSMutableString stringWithString:rest];
        [next appendString:[rest substringWithRange:NSMakeRange(i, 1)]];
        [remaing deleteCharactersInRange:NSMakeRange(i, 1)];
        [self perm:next andRest:remaing];
    }
    if ([rest isEqual:@""]) {
        NSLog(@"%@", sofar);
        i++;
    }
}
- (void)permutation:(NSString*)str{
    NSMutableString *str1 = [NSMutableString string];
    NSMutableString *str2 = [NSMutableString stringWithFormat:@"%@", str];
    [self perm:str1 andRest:str2];
    NSLog(@"%d", i);
}
@end

#import "Permutation.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        /*
         全排列 abcd
        */
        Test *test = [[Test alloc] init];
        [test permutation:@"abc"];
    }
    return 0;
}

相关文章

  • 全排列与字典序

    全排列 递归实现全排列; 首先来说递归算法实现全排列: 例如,对于{1,2,3,4}的例子进行全排列,其可以分解...

  • 全排列

    求全排列最简单的就是递归了123 的全排列共有 6 个, 123 的全排列等于以 1 开头 23 的全排列, 加上...

  • 全排列

    题目 输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排...

  • 全排列

    递归的版本image.png

  • 全排列

  • 全排列

  • 全排列

    给出一个列表[1,2,3],其全排列为: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,...

  • 全排列

    给定一个数字列表,返回其所有可能的排列。

  • 全排列

    给定一个没有重复数字的序列,返回其所有可能的全排列。 示例: 输入: [1,2,3]输出:[[1,2,3],[1,...

  • 全排列

    两种方法:第一种方法:递归: 从集合中依次选出每一个元素,作为排列的第一个元素,然后对剩余的元素进行全排列,如此递...

网友评论

      本文标题:全排列

      本文链接:https://www.haomeiwen.com/subject/qgffsttx.html