问题:给定一个正整数n,产生Pascal三角形的前n行。
OC算法实现:
//
// PascalTriangle.h
// Algorithm
//
// Created by han shuai on 2016/9/27.
// Copyright © 2016年 han shuai. All rights reserved.
//
/**
20
*/
#import <Foundation/Foundation.h>
@interface PascalTriangle : NSObject
- (NSMutableArray *)pascalTriangle:(int)n;
@end
//
// PascalTriangle.m
// Algorithm
//
// Created by han shuai on 2016/9/27.
// Copyright © 2016年 han shuai. All rights reserved.
//
#import "PascalTriangle.h"
@implementation PascalTriangle
- (NSMutableArray *)pascalTriangle:(int)n
{
NSMutableArray *triangle = [NSMutableArray array];
for (int i = 0; i < n; i++) {
NSMutableArray *line = [NSMutableArray array];
for (int j = 0; j< i+1; j++) {
int value = 0;
if (j == 0) {
value = 1;
}
else if (j == i) {
value = 1;
}
else
{
//获取上一行
NSMutableArray *upline = triangle[i-1];
value = [upline[j] intValue] + [upline[j-1] intValue];
}
[line addObject:[NSNumber numberWithInt:value]];
}
[triangle addObject:line];
}
return triangle;
}
@end