static int count = 0;
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
int temp[100] = {0};
int n = 5;
int sum = 1;
int tempN = n;
while (n>0) {
sum = sum*n;
n--;
}
printf("总共:%d\n",sum);
fullArray(tempN,temp,0);
}
//n 为输入的需要全排列的数 temp为临时数组 tempIndex 为下标值
void fullArray(int n,int * temp,int tempIndex) {
if (n == 0) {
printf("count = %d: ",++count);
for (int i = 0; i<tempIndex; i++) {
printf(" %d ",temp[i]);
}
printf("\n");
}else {
for (int i = 1; i<= n+tempIndex; i++) {
// 看是否可以放下一个值
BOOL isCanJoinData = YES;
for (int k = 0; k<=tempIndex; k++) {
if (i == temp[k]) {
isCanJoinData = NO;
break;
}
}
if (isCanJoinData) {
temp[tempIndex] = i;
fullArray(n-1,temp,tempIndex+1);
temp[tempIndex] = 0;
}
}
}
}
@end
递归8_全排列
最新推荐文章于 2021-02-05 08:46:44 发布