牛的数+字符串全排列

版权声明:有一些内容粘贴之后变成图片如果需要原文原视频 可以联系我 https://blog.csdn.net/wodemale/article/details/89737359

母牛每年生一只母牛,新出生的母牛成长三年后也能每年生一只母牛,假设不会死。
求N年后,母牛的数量。

public static int cowNumber1(int n) {
	if (n < 1) {
		return 0;
	}
	if (n == 1 || n == 2 || n == 3) {
		return n;
	}
	//去年的牛(牛不死)+ 三年前出生现在可以生的牛
	return cowNumber1(n - 1) + cowNumber1(n - 3);
}

//方法2
    public static int cowNumber2(int n) {
   		if (n < 1) {
   			return 0;
   		}
   		if (n == 1 || n == 2 || n == 3) {
   			return n;
   		}
   		int res = 3;
   		int pre = 2;
   		int prepre = 1;
   		int tmp1 = 0;
   		int tmp2 = 0;
   		for (int i = 4; i <= n; i++) {
   			tmp1 = res;
   			tmp2 = pre;
   			res = res + prepre;
   			pre = tmp1;
   			prepre = tmp2;
   		}
   		return res;
   	}

1、打印一个字符串的全部排列
2、打印一个字符串的全部排列,要求不要出现重复的排列

public static void printAllPermutations1(String str) {
	char[] chs = str.toCharArray();
	process1(chs, 0);
}

public static void process1(char[] chs, int i) {
	if (i == chs.length) {
		System.out.println(String.valueOf(chs));
	}
	for (int j = i; j < chs.length; j++) {
		swap(chs, i, j);
		process1(chs, i + 1);
		swap(chs, i, j);
	}
}

public static void printAllPermutations2(String str) {
	char[] chs = str.toCharArray();
	process2(chs, 0);
}

public static void process2(char[] chs, int i) {
	if (i == chs.length) {
		System.out.println(String.valueOf(chs));
	}
	HashSet<Character> set = new HashSet<>();
	for (int j = i; j < chs.length; j++) {
		if (!set.contains(chs[j])) {
			set.add(chs[j]);
			swap(chs, i, j);
			process2(chs, i + 1);
			swap(chs, i, j);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/wodemale/article/details/89737359