经典算法_杨辉三角,集合法
代码编写环境:VSCode2017
杨辉三角:
#include<stdio.h>
int main() {
int a[10][10];
int i,j;
//1、给二维数组赋初值
for (i = 0; i < 10; i++)
{
for (j = 0; j <= i; j++)
{
a[i][j] = 0;
}
}
//2、给二维数组的第一列和对角线赋值1
for (i = 0; i < 10; i++)
{
a[i][0] = 1;
a[i][i] = 1;
}
//3、按照杨辉三角规律,进行循环运算
/* 1
1 1
1 2 1
1 3 3 1
a[2][1] = a[1][0] + a[1][1]
||
a[2][1] = a[2-1][1-1] + a[2-1][1]
*/
for (i = 2; i < 10; i++)
{
for ( j = 1; j < i; j++)
{
a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
}
}
//4、打印结果
for (i = 0; i < 10; i++)
{
for (j = 0; j <= i; j++)
{
printf("%5d",a[i][j]);
}
printf("
");
}
}
================指针比较三数法================
#include<stdio.h>
void swap(int *,int *);
int main(){
int a,b,c;
a = 3;
b = 2;
c = 1;
int *p1,*p2,*p3;
p1 = &a;
p2 = &b;
p3 = &c;
if(a>b){
swap(p1,p2);
}
if(a>c){
swap(p1,p3);
}
if(b>c){
swap(p3,p2);
}
printf("%d %d %d",a,b,c);
}
void swap(int *s1,int *s2){
int t;
t = *s1;
*s1 = *s2;
*s2 = t;
}
结果:
Java底层是C,语言对比一下,会更好。
JVM的本地方法栈
1.c语言的int类型数组默认赋初值-858993460,java则赋0。
2.c语言的int a[10][10];的长度不能为变量,只能是常量,java则可以, int[] arr = new int[n];
Java语言:
代码编写环境:IDEA2018
数组法
package com.m.suan_pai;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请属于一个大于0的整数");
int n = scanner.nextInt();
if (n <= 0) {
throw new NumberFormatException(n + "<=0");
}
test(n);
}
public static void test(int n) {
int[][] a = new int[n][n];
for (int i = 0; i < n; i++) {
a[i][0] = 1;
a[i][i] = 1;
}
for (int i = 2; i < n; i++) {
for (int j = 1; j < i; j++) {
a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
}
}
//4、打印结果
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
System.out.printf("%5d", a[i][j]);
}
System.out.printf("
");
}
}
}
集合法:
package com.m.pascals_triangle;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class PascalsTriangle_List {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入:");
int n = scanner.nextInt();
for (List<Integer> list : generate(n)) {
System.out.println(list);
}
}
public static List<List<Integer>> generate(int numRows) {
if (numRows <= 0) {
throw new NumberFormatException(numRows + "<=0");
}
List<List<Integer>> lists = new ArrayList<>();
lists.add(new ArrayList<>());
lists.get(0).add(1);
if (numRows == 0) {
return lists;
}
for (int i = 1; i < numRows; i++) {
List<Integer> list = new ArrayList<>();
List<Integer> preList = lists.get(i - 1);
list.add(1);
for (int j = 1; j < i; j++) {
int result = preList.get(j - 1) + preList.get(j);
list.add(result);
}
list.add(1);
lists.add(list);
}
return lists;
}
}