首页 > 试题广场 >

杨辉三角

[编程题]杨辉三角
  • 热度指数:3249 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
上面的图形熟悉吗?它就是我们中学时候学过的杨辉三角。

输入描述:
输入数据包含多组测试数据。

每组测试数据的输入只有一个正整数n(1≤n≤128),表示将要输出的杨辉三角的层数。

输入以0结束


输出描述:
对应于每一个输入,请输出相应层数的杨辉三角,每一层的整数之间用一个空格隔开,每一个杨辉三角后面加一个空行。
示例1

输入

2
3
0

输出

1
1 1

1
1 1
1 2 1
/*针对128这种情况下,java 中的long很明显不够用,但好在有BigInteger这个针对大数据的类
*   故此题利用 BigInteger类可以轻松解决。代码如下
*/
import java.math.BigInteger;
import java.util.*;
public class Main{
    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        int n=Integer.valueOf(sc.nextLine());
        
        while(n!=0){
          BigInteger num[][]=new BigInteger[n][n];
          
         for(int i=0;i<n;i++){
        	 for(int j=0;j<n;j++){
        		 num[i][j]=BigInteger.ZERO;
        	 }
         }
          
            for(int k=0;k<n;k++){
                num[k][0]=BigInteger.ONE;
                num[k][k]=BigInteger.ONE;
            }
            if(n>=3){
                for(int m=2;m<n;m++){
                    for(int p=1;p<=n-1;p++){
                    	num[m][p]=num[m-1][p-1].add(num[m-1][p]); 
                    }
                }
            }
            for(int i=0;i<n;i++){
                for(int j=0;j<=i;j++){
                	if(j==0){
                		System.out.print(num[i][j]);
                	}else{
                		System.out.print(" "+num[i][j]+"");
                	}
                }
                System.out.println();
            }
            System.out.println();
            n=Integer.valueOf(sc.nextLine());
            num=null;
        }
    }
}

编辑于 2015-12-08 23:27:18 回复(0)
Java
//BigInteger
//开好数组后,从上往下扫描只扫描一次
//凡涉及大数复杂度的,提交前先自己用System.currentTimeMillis()测测时间
import java.math.BigInteger;
import java.util.Scanner;

public class 杨辉三角 {
public static void main(String[] args) {  Scanner sc=new Scanner(System.in);  while(sc.hasNext()){  int n=sc.nextInt();  if(n==0){  break;  }  BigInteger[][] array=new BigInteger[n][1];  for(int i=1;i<=n;i++){  array[i-1]=new BigInteger[i];  }  for(int i=0;i<array.length;i++){  array[i][0]=BigInteger.ONE;  array[i][array[i].length-1]=BigInteger.ONE;  System.out.print(array[i][0]+" ");  for(int j=1;j<array[i].length-1;j++){  array[i][j]=array[i-1][j].add(array[i-1][j-1]);  System.out.print(array[i][j]+" ");  }  if(i==0){  System.out.println();  }else{  System.out.println(1);  }  }  System.out.println();  }  sc.close();  }
}

编辑于 2018-11-19 12:36:37 回复(0)
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			int n = sc.nextInt();
			if(n == 0) break;
			BigInteger[][] arr = new BigInteger[n][n];
			for (int i = 0; i < n; i ++ ) {
				arr[i][0] = BigInteger.valueOf(1);
				for (int j = 1; j < i + 1; j ++ ) {
					if(j == i) arr[i][j] = arr[i][0];
					else arr[i][j] = arr[i - 1][j - 1].add(arr[i - 1][j]);
				}
			}
			for (int i = 0; i < n; i ++ ) {
				for (int j = 0; j < i + 1; j ++ ) {
					if(j == i) System.out.println(arr[i][j]);
					else System.out.print(arr[i][j] + " ");
				}
			}
			System.out.println();
		}
	}
}

发表于 2016-10-15 23:46:39 回复(0)
本来想用long double类型,结果精度不达标……
用字符串模拟大整数加法
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<functional>
#include <map>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <exception>
#include <iomanip>

using namespace std;

string add(string& s1,string& s2)
{
	int m = s1.size(), n = s2.size();
	int i = m - 1, j = n - 1;
	int carry = 0;
	string res = "";
	while (i >= 0 && j >= 0)
	{
		int num = s1[i] - '0' + s2[j] - '0' + carry;
		if (num >= 10){carry = 1;num -= 10;}
		else carry = 0;
		res = to_string(num) + res;
		--i; --j;
	}
	while (i >= 0)
	{
		int num = s1[i] - '0' + carry;
		if (num >= 10){ carry = 1; num -= 10; }
		else carry = 0;
		res = to_string(num) + res;
		--i;
	}
	while (j >= 0)
	{
		int num = s2[j] - '0' + carry;
		if (num >= 10){ carry = 1; num -= 10; }
		else carry = 0;
		res = to_string(num) + res;
		--j;
	}
	if (carry == 1) res = "1" + res;

	return res;
}

int main(int argc, char** argv)
{
	vector<vector<string>> ***(128);
	***[0] = vector<string>{"1"};
	***[1] = vector<string>{"1", "1"};
	for (int i = 2; i < 128; ++i)
	{
		***[i] = vector<string>(i + 1);
		***[i][0] = ***[i][i] = "1";
		for (int j = 1; j <= i - 1; ++j)
		{
			***[i][j] = add(***[i - 1][j - 1],***[i - 1][j]);
		}
	}
	int n;
	while (cin >> n && n > 0)
	{
		for (int i = 0; i < n; ++i)
		{
			for (int j = 0; j < i; ++j) cout << ***[i][j] << " ";
			cout << ***[i][i] << endl;
		}
		cout << endl;
	}
	return 0;
}

发表于 2017-07-08 18:41:04 回复(0)
BigInteger  []a = new BigInteger[8257];
  a[0] = a[1] = a[2] = BigInteger.valueOf(1);
  int n;
  int i;
  int j;
  int sum = 0;
  int h;  
  for (i = 3;(((i - 1)*i) / 2) + (i - 1) <=8256; i++) {
   a[(int)(((i - 1)*i) / 2)] =BigInteger.valueOf(1);
   a[(int)((((i - 1)*i) / 2) + (i - 1))] = BigInteger.valueOf(1);
   
  }
  i = 3;
  j = 0;
  h = -2;
  for (sum = 3; sum <= 8255; sum++) {
   if ((sum == ((i - 1)*i) / 2))
    continue;
   else if ((sum == (((i - 1)*i) / 2) + (i - 1))) {
    i++;
   }
   else {
    a[sum] = a[(sum+h)/ 2].add(a[(sum+j)/2]) ;
    j++;
    h++;
   }
  }
发表于 2019-05-15 10:51:52 回复(0)
#include <bits/stdc++.h>
using namespace std;

string add (string a, string b) {
    int inc = 0, i, j, alen = a.size(), blen = b.size();
    string res;
    for (i = alen - 1, j = blen - 1; i >=0 || j >= 0;) {
        if (i < 0 && j >= 0) {
            int tmp = b[j] - '0' + inc;
            res += tmp % 10 + '0';
            inc = tmp / 10;
            --j;
        }
        else if (i >= 0 && j < 0) {
            int tmp = a[i] - '0' + inc;
            res += tmp % 10 + '0';
            inc = tmp / 10;
            --i;
        }
        else {
            int tmp = a[i] - '0' + b[j] - '0' + inc;
            inc = tmp / 10;
            res += tmp % 10 + '0';
            --i, --j;
        }
    }
    if (inc == 1) 
        res += '1';
    reverse (res.begin(), res.end());
    return res;
}

int main() {
    int n, i, j;
    while (cin >> n && n > 0) {
        string a[128][128];
        for (i = 0; i < n; ++i) { 
            for (int j = 0; j <= i; ++j) {
                if (i == j || j == 0) 
                    a[i][j] = "1"; 
                else
                    a[i][j] = add(a[i - 1][j - 1], a[i - 1][j]); 
                i > j ? cout << a[i][j] << ' ' : cout << a[i][j] << endl;
            }
        }
        cout << endl;
    }
    return 0;
}

发表于 2018-02-21 10:32:00 回复(0)
def t():
    L = [1]
    while 1:
        yield ' '.join(map(str, L))
        L.append(0)
        s = len(L)
        L = [L[i - 1] + L[i] for i in xrange(s)]    
try:
    while 1:
        gen = t()
        n = input()
        if n == 0:
            break
        for j in xrange(n):
            print next(gen)
        print ''
except:
    pass

发表于 2016-12-28 15:17:33 回复(0)
#include<vector>
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
string add_operation(string &s1,string &s2){
    int len1=s1.size(),len2=s2.size();
    int len = max(len1,len2);
    int minlen = min(len1,len2);
    int carry=0;
    string res;
    for(int i=1;i<=minlen;i++){
        int val = (s1[len1-i]-'0')+(s2[len2-i]-'0')+carry;
        char c = val%10+'0';
        res.push_back(c);
        carry=val/10; 
    }
    int temp = len-minlen;
    if(len==len2){
        for(int i=temp-1;i>=0;i--){
            int val = s2[i]-'0'+carry;
            char c = val%10+'0';
            res.push_back(c);
            carry=val/10;                 
        }
    }else{
        for(int i=temp-1;i>=0;i--){
            int val = s1[i]-'0'+carry;
            char c = val%10+'0';
            res.push_back(c);
            carry=val/10;                 
        }
    }
    if(carry)res.push_back('1');
    reverse(res.begin(),res.end());
    return res;
}
//本题主要考察数据溢出和大数字处理的概念,c++不像java或python有大数字处理类或标准库,需要自己实现
int main(){
    //方式一:适用于n较小时(基本数据类型),本题中明显这种方式是不行的,正整数n(1≤n≤128)
    /*
    int n;
    vector<vector<unsigned long long> > res;
    vector<unsigned long long> ans;
    ans.push_back(1);
    res.push_back(ans);
    ans.push_back(1);
    res.push_back(ans);
    while(scanf("%d",&n)!=EOF){
        if(n==0)break;
        int len = res.size();
        for(int i=len;i<n;i++){
            ans.clear();
            ans.push_back(1);
            vector<unsigned long long> backV = res.back();
            int size = backV.size()-1;
            for(int i=0;i<size;i++){
                unsigned long long val = backV[i]+backV[i+1];
                ans.push_back(val);
            }
            ans.push_back(1);
            res.push_back(ans);
        }
        //输出
        for(int i=0;i<n;i++){
            int size = res[i].size();
            for(int j=0;j<size;j++){
                printf("%llu",res[i][j]);
                if(j!=size-1){
                    printf(" ");
                }else{
                    printf("\n");
                }
            }
        }
        printf("\n");  //空一行
    }
    */
    
    
    //方式二:利用字符串来储存数,并且进行加法计算  (50ms,9080k)
    int n;
    vector<vector<string> >res;
    vector<string> ans;
    ans.push_back("1");
    res.push_back(ans);
    ans.push_back("1");
    res.push_back(ans);
    while(scanf("%d",&n)!=EOF){
        if(n==0)break;
        int len = res.size();
        for(int i=len;i<n;i++){
            ans.clear();
            ans.push_back("1");
            vector<string> backV = res.back();
            int size = backV.size()-1;
            for(int i=0;i<size;i++){
                string s = add_operation(backV[i],backV[i+1]);
                ans.push_back(s);
            }
            ans.push_back("1");
            res.push_back(ans);
        }
        //输出
        for(int i=0;i<n;i++){
            int size = res[i].size();
            for(int j=0;j<size;j++){
                cout<<res[i][j];
                if(j!=size-1){
                    cout<<" ";
                }else{
                    cout<<endl;
                }
            }
        }
        cout<<endl;
    }
    return 0;
}

发表于 2016-06-26 21:46:32 回复(0)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define Max 130
#define Max1 1000
char a[Max][Max][Max1];
void BigAddBig(char *a,char *b,char *res)
{
    int aint[Max1];
    int bint[Max1];
    int c[Max1];
    memset(c,0,sizeof(c));
    memset(aint,0,sizeof(aint));
    memset(bint,0,sizeof(bint));
    int alen = strlen(a);
    int blen = strlen(b);
    int i;
    for(i=0;i<alen;i++)
        aint[i] = a[alen-i-1] - '0';

    for(i=0;i<blen;i++)
        bint[i] = b[blen-i-1] - '0';
    int len = alen>blen?alen:blen;
    int t = 0;
    for(i=0;i<len;i++)
    {
        c[i] = aint[i] + bint[i] + t;
        t = c[i]/10;
        c[i] = c[i]%10;
    }
    if(t!=0)
    {
        c[len] = t;
        len++;
    }
    for(i=0;i<len;i++)
    {
        res[i] = c[len-i-1] + '0';
    }
    res[len] = '\0';
}
void init()
{
    int i=0;
    int j=0;
    for(i=0;i<Max;i++)
        for(j=0;j<Max;j++)
            strcpy(a[i][j],"0");
    for(i=1;i<=128;i++)
    {
        strcpy(a[i][1],"1");
        for(j=2;j<=i;j++)
        {
            BigAddBig(a[i-1][j-1],a[i-1][j],a[i][j]);
        }
    }
}
int main()
{
    init();
    int n;
    int i;
    int j;
    while(scanf("%d",&n)!=EOF)
    {
        if(n == 0)
            break;
        for(i=1;i<=n;i++)
        {
            printf("%s",a[i][1]);
            for(j=2;j<=i;j++)
            {
                printf(" %s",a[i][j]);
            }
            printf("\n");
        }
        printf("\n");
    }
    return 0;
}
c语言数组模拟大数相加
发表于 2016-01-19 15:03:18 回复(0)
用string来模拟大数加法。
#include <iostream>
#include <string>
using namespace std;

string strplus(string & a, string & b)
{
	string temp = (a.length() > b.length() ? a : b);
	int c = 0, index = temp.length() - 1;
	for (int i = a.length() - 1, j = b.length() - 1; i >= 0 || j >= 0; --i, --j)
	{
		temp[index] = (i >= 0 ? a[i] - '0' : 0) + (j >= 0 ? b[j] - '0' : 0) + c;
		c = temp[index] / 10;
		temp[index] = temp[index] % 10 + '0';
		--index;
	}
	string map[10] = { "0","1","2","3","4","5","6","7","8","9" };
	if (c)
		temp = map[c] + temp;
	return temp;
}

int main()
{
	string table[129][129] = { "1" };
	for (int i = 1; i <= 128; ++i)
	{
		table[i][0] = "1";
		for (int j = 1; j <= i; ++j)
			table[i][j] = strplus(table[i - 1][j], table[i - 1][j - 1]);
	}

	int n;
	while (cin >> n && n)
	{
		for (int i = 0; i < n; ++i)
		{
			for (int j = 0; j <= i; ++j)
				cout << (j ? " " : "") << table[i][j];
			cout << endl;
		}
		cout << endl;
	}

	return 0;
}

发表于 2015-12-15 10:09:48 回复(0)
#include <iostream>
#include <limits.h>
using namespace std;
long int intArray[128][128] = { 0 };
void InitArray(int numberCount = 1)
{
for (int lineCount = 0; lineCount <= numberCount; lineCount++)
intArray[lineCount][0] = 1;
intArray[1][1] = 1;
for (int lineCount = 1; lineCount <= numberCount; lineCount++)
{
for (int dCount = 1; dCount < numberCount; dCount++)
intArray[lineCount][dCount] = intArray[lineCount - 1][dCount]
+ intArray[lineCount - 1][dCount - 1];
intArray[numberCount][numberCount] = 1;
}
}
void Print(int count)
{
int temp = count;
for (int dCount = 0; dCount < count; dCount++)
cout << intArray[temp][dCount] << " ";
cout << intArray[temp][temp];
}
int YangHuiSanJiaoTest()
{
int line;
cin >> line;
if (line < 1)
{
return 0;
}
InitArray(line);
for (int lineCount = 0; lineCount < line; lineCount++)
{
Print(lineCount);
cout << endl;
}
return 0;
}
int main()
{
 YangHuiSanJiaoTest();
    return 0;
}
为何提示 2 没通过
2
1
1  1
发表于 2015-11-24 19:13:39 回复(0)
/*这道题需要注意以下几点:
1、这道题主要还是对大数据的处理,和斐波那契数列有点像,
给的测试用例都比较大,用基本的int,long之类的根本就
不行,long型的最多到68,就超了,题目给的要求是1≤n≤128,
所以这个题主要是看如何操作这种比较大的数值。Java里面
提供了一个很强大的BigInteger,这个类可以处理任意大
的数字,里面有好多方法,可以查查JDK多了解一下关于这个
类的用法,可以解决好多比较大的数字的问题。
2、然后就是这个题的思想,仔细观察,
可以发现这样一个规律,rs[i][j]=rs[i-1][j]+rs[i-1][j-1]);
我们可以利用这个规律在一个二维矩阵中动态打表,
最后输出这个二维矩阵中不为零的数字即可。
3、输出格式的问题:题目中让每行数字之间用空格隔开,
那么我们需要注意在每一行的最后一个数字后面是不能加空格的,
由于空格我们看不见,所以打印出来看上去和答案一样,但是会报错,
就是因为多了一个空格,我举个例子,
比如我用“*”代替空格,便于观察,如下输出:
1*
1*1*
1*2*1*
1*3*3*1*
如果将“*”换成“ ”感觉和题目的输出一样,
其实是每行末尾多了一个空格,所以这个要注意。
*/
下面我贴上自己的代码:
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
 Scanner sc=new Scanner(System.in);
 while(sc.hasNext()){
 int n=sc.nextInt();
 if(n==0){
  break;
 }
 BigInteger [][] rs=new BigInteger[n][n];
 for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
       rs[i][j] = new BigInteger("0");
      }
    } 
 for (int i = 0; i < rs.length; i++) {
  rs[i][0]=new BigInteger("1");
 }
 for (int i = 1; i < rs.length; i++) {
  for (int j = 1; j < i+1; j++) {
   rs[i][j]=rs[i-1][j].add(rs[i-1][j-1]);
  }
 }
 StringBuffer sb=new StringBuffer();
 for (int i = 0; i < rs.length; i++) {
  for (int j = 0; j < i+1; j++) {
    sb.append(rs[i][j]+"*");
  }
  System.out.println(sb.substring(0, sb.length()));
  sb.replace(0, sb.length(), "");
 }
 System.out.println();
 }
}
}

编辑于 2015-11-22 14:59:36 回复(0)
因为数据量过大,所以使用BigInteger
class Main
{

    public static void format(int m)
    {
        String[] array=new String[m];
        for(int i=0;i<array.length;i++)
        {
            array[i]="0";
        }
        array[0]="1";
        String a="1";
        String c="1";
        System.out.println("1");
        for(int i=1;i<m;i++)
        {
            int j=1;
            for( j=1;j<=i;j++)
            {
                array[j-1]=a;
                BigInteger aa=new BigInteger(c);
                BigInteger bb=new BigInteger(array[j]);
                a=aa.add(bb).toString();
                c=array[j];
            }
            array[j-1]="1";
            System.out.print(array[0]);
            for( int k=1;k<=i;k++)
            {
                System.out.print(" "+array[k]);
            }
            System.out.println();
            a="1";
            c="1";
        }
    }
    public static void main(String[] args)
    {
        Scanner scanner=new Scanner(System.in);
        int m=scanner.nextInt();
        while(m!=0)
        {
            format(m);
            System.out.println();
            m=scanner.nextInt();
        }
    }
}

发表于 2015-10-30 20:04:40 回复(0)
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class Main {
	public static void main(String[] args) {
		Reader reader = new InputStreamReader(System.in);
		StringBuilder sb = new StringBuilder();
		try {
			char c =  ' ';
			while ((c = (char)reader.read()) != '0') {
				sb.append(c);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		String[] nums = new String(sb).split(" ");
		for(int i=0;i<nums.length;i++){
			printArray(yanHuiSanJiao(Integer.parseInt(nums[i])));
			System.out.println();
		}
	}

	public static int[][] yanHuiSanJiao(int n) {
		int[][] a = new int[n][n];
		for (int i = 0; i < n; i++) {
			a[i][0] = 1;
		}
		for (int i = 1; i < n; i++) {
			for (int j = 1; j <= i; j++) {
				a[i][j] = a[i - 1][j] + a[i - 1][j - 1];
			}
		}
		return a;
	}

	public static void printArray(int[][] arr) {
		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j <= i; j++) {
				System.out.print(arr[i][j] + " ");
			}
			System.out.println();
		}
	}
}

在eclipse中可以运行,在这里运行出错,搞不懂。。

发表于 2015-10-24 12:10:30 回复(0)
//1,超出整数范围的数据的运算应该用字符串模拟
//2,杨辉三角中,除去两边的1,中间的数字都等于其肩上两个数的和
//3,这里用到了惰性加载,并不是一次就把所有可能需要的杨辉三角计算出来,而是在不断扩展。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string big_add(const string &str1, const string &str2) {
    const string &shorter = str1.size() > str2.size() ? str2 : str1;
    const string &longer = str1.size() > str2.size() ? str1 : str2;
    string result;
    int carry = 0;
    auto c1 = longer.rbegin(), c2 = shorter.rbegin();
    for (;c2 != shorter.rend();++c1, ++c2) {
        int temp = *c1 + *c2 + carry - '0' * 2;
        carry = temp / 10;
        result.insert(result.begin(), temp % 10+'0');
    }
    for (;c1 != longer.rend();c1++) {
        int temp = *c1 + carry - '0';
        carry = temp / 10;
        result.insert(result.begin(), temp % 10+'0');
    }
    if (carry != 0) {
        result.insert(result.begin(), carry+'0');
    }
    return result;

}
void get_YHT(vector<vector<string>> &yht,int n) {
    if (n < yht.size()) {
        return;
    }
    for (int i = yht.size();i <= n;i++) {
        vector<string> newfloor = { "1" };
        for (int j = 0;j < yht[i - 1].size()-1;j++) {
            string temp=big_add(yht[i - 1][j], yht[i - 1][j + 1]);
            newfloor.push_back(temp);
        }
        newfloor.push_back("1");
        yht.push_back(newfloor);
    }
}
int main() {
    vector<vector<string>> yht{ {"1"},{"1","1"},{"1","2","1"} };
    int n;
    while (cin >> n) {
        if (n == 0) {
            break;
        }
        get_YHT(yht,n);
        for (int i = 0;i < n;i++) {
            for (auto j = yht[i].begin();j != yht[i].end();j++) {
                cout << *j;
                if (j == yht[i].end() - 1)
                    cout << "\n";
                else
                    cout << " ";
            }
        }
        cout << endl;
    }
}
编辑于 2015-10-03 16:05:19 回复(0)
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

string addStr(string &x,string &y)
{
	int i,j,sizeX=x.size(),sizeY=y.size();
	int flag=0;
	i=sizeX-1,j=sizeY-1;
	string s;

	while(i>=0&&j>=0)
	{
		s.push_back(((x[i]+y[j]+flag-'0'-'0')%10)+'0');
		flag=(x[i]+y[j]+flag-'0'-'0')/10;
		i--,j--;
	}
	//
	while(i>=0)
	{
		s.push_back(((x[i]+flag-'0')%10)+'0');
		flag=(x[i]+flag-'0')/10;
		i--;
	}
	//

	while(j>=0)
	{
		s.push_back(((y[j]+flag-'0')%10)+'0');
		flag=(y[j]+flag-'0')/10;
		j--;
	}

	if(flag)
		s.push_back(flag+'0');
	reverse(s.begin(),s.end());

	return s;
}
int main()
{
	int n,i,j;
	string s1,s2;
	int cnt=0,size;
	vector<string> tmp;
	vector<vector<string>> res;
	while(cin>>n)
	{
		tmp.clear(),res.clear();
		if(n==0)
			break;
		//
		if(n==1)
		{
			cout<<"1"<<endl;
			continue;
		}
		//
		
		tmp.push_back("1");
		res.push_back(tmp);
		for(i=1;i<n;i++)
		{
			tmp.clear();
			tmp.push_back("1");
			for(j=2;j<=i;j++)
				tmp.push_back(addStr(res[i-1][j-2],res[i-1][j-1]));
			tmp.push_back("1");
			res.push_back(tmp);
		}
		//
		for(i=0;i<n;i++)
		{
			for(j=0;j<res[i].size()-1;j++)
				cout<<res[i][j]<<" ";
			cout<<res[i][res[i].size()-1];
			cout<<endl;
		}
		cout<<endl;
	}
	//
	system("pause");
	return 0;
}

发表于 2015-09-22 22:23:46 回复(0)
public static void printTriangle(int n){
		List<BigDecimal> list = new ArrayList<>(n);
		System.out.println("1");
		for(int i=1;i<n;i++){
			BigDecimal pre = BigDecimal.ZERO;
			list.add(new BigDecimal(1));
			for(int j=0;j<i;j++){
				BigDecimal temp = list.get(j);
				BigDecimal res = temp.add(pre);
				pre = temp;
				list.set(j, res);
				System.out.print(res+" ");
			}
			System.out.println("1");
		}
		System.out.println();
	}

发表于 2015-09-17 15:32:22 回复(2)
// write your code here cpp

#include <stdio.h>
#include <string.h>

#define min(x, y) ((x)<(y) ? (x) : (y))

//for every number in string
//len ..digits .. '\0' 
#define N 40
char ***[128][N];
unsigned char head[128];

void add(int a, int b, int n)
{
    //*a will change
    int h = min(head[a], head[b]) - 1;

    for(int i=n-2, car=0; i>=h; --i){
        ***[a][i] += ***[b][i]-2*'0'+car;
        car = ***[a][i]/10;
        ***[a][i] = ***[a][i]%10 + '0';
    }

    if(***[a][h] != '0')
        head[a] = h;
    else
        head[a] = h + 1;
}
 
int main()
{
    int n;
    while(~scanf("%d", &n)){
        if(n==0) break;

        memset(***, '0', sizeof(***));
        memset(head, N-1, sizeof(head));

        for(int i=1; i<=n; ++i){
            for(int j=i-1; j>=0; --j)
                if(j == i-1 || j == 0){
                    ***[j][N-2] = '1';
                    ***[j][N-1] = '\0';
                    head[j] = N-2;
                }else
                    add(j, j-1, N);

            for(int j=0; j<i; ++j)
                printf("%s%c", &***[j][head[j]], j==i-1?'\n':' ');
        }

        printf("\n");
    }

    return 0;
}

发表于 2015-09-12 21:33:15 回复(0)
#include"stdio.h"
 void yanghui(const int n)
 {
    int i,j;
     long int a[128][128]={0};
  for(i=0;i<n;i++)
{
a[i][0]=1;
    a[i][i]=1;
}    
for(i=2;i<n;i++)
{
for(int j=1;j<i;j++)
a[i][j]=a[i-1][j-1]+a[i-1][j];
}     
    for(i=0;i<n;i++)
{
for( j=0;j<=i;j++)
printf("%ld ",a[i][j]);
printf("\n");
}
}      
int main()
{
    int i,j,n;
    scanf("%d",&n);
    while((n>=1)&&(n<=128)){
        
        yanghui(n);
        printf("\n");
         scanf("%d",&n);
    }    
    
   return 0; 
    
}
128测试没通过,怎么改

发表于 2015-09-04 11:08:28 回复(2)
L0L头像 L0L
//要使用string存放数据,long不足以存放最后的和 
#include<iostream>
#include<vector>
using namespace std;
string add(string s1,string s2){
	int len=s1.length()>s2.length()?s1.length():s2.length();
	int min=s1.length()<s2.length()?s1.length():s2.length();
	string ret(len+1,'0');
	int carry=0;
	while(len-1>=0){
	 if(s1.length()>s2.length()){
		if(min-1>=0){
			ret[len]=(s1[len-1]+s2[min-1]-'0'-'0'+carry)%10+'0';
			carry=(s1[len-1]+s2[min-1]-'0'-'0'+carry)/10;
		}else{
			ret[len]=(s1[len-1]-'0'+carry)%10+'0';
			carry=(s1[len-1]-'0'+carry)/10;
		}
	}
	else{
		if(min-1>=0){
			ret[len]=(s2[len-1]+s1[min-1]-'0'-'0'+carry)%10+'0';
			carry=(s2[len-1]+s1[min-1]-'0'-'0'+carry)/10;
		}else{
			ret[len]=(s2[len-1]-'0'+carry)%10+'0';
			carry=(s2[len-1]-'0'+carry)/10;
		}
	}
		--len;
		--min;
	}
	if(carry==1)
		ret[0]='1';
	else
		ret.erase(0,1);
	return ret;
}
int main(){
	vector<vector<string>> v;
	vector<string> tmp;
	int i,j;
	int n;
	tmp.push_back("1");
	v.push_back(tmp);
	tmp.clear();
	tmp.push_back("1");
	tmp.push_back("1");
	v.push_back(tmp);
	for(i=2;i<130;i++){
		tmp.clear();
		for(j=0;j<i+1;++j){
			if(j==0||j==i)
				tmp.push_back("1");
			else{
				tmp.push_back(add(v[i-1][j-1],v[i-1][j]));
			}
		}
		v.push_back(tmp);
	}
	scanf("%d",&n);
	while(n!=0){
		for(i=0;i<n;++i){
			printf("%s","1");
			for(j=1;j<v[i].size();j++){
				printf(" %s",v[i][j].data());
			}
			printf("\n");
		}
		printf("\n");
		scanf("%d",&n);
	}
	return 0;
} 

发表于 2015-08-28 15:54:47 回复(0)