题目:
给定一个正整数n,输出外观数列的第n项。
“外观数列”是一个整数序列,从数字1开始,序列中的每一项都是对前一项的描述。
你可以将其视作是递归共识定义的数字字符串序列:
- contAndSay(1) = “1”;
- countAndSay(n) 是对countAndSay(n-1)得描述,然后转换成另外一个数字字符串。
前五项如下:
1 = "1"
2 = "11" //这里的第一个1,是描述第二个1的作用。读作:一个1
3 = “21” //依照第一位数字描述后一位的数字,读作:二个1
4 = “1211” //读作:一个2 和 一个1;
5 = “111221” //读作: 一个1,一个2,二个1
解题思路
首先就是将传入的值,进行拆解。先从1-n进行描述,一个变量存储当的数值,一个存储当钱数值的个数。
将n-1递归传入函数,一步一步转换成字符串在加入当前字符串的结尾。
假设传入的数值是9.
public String countAndSay(int n){
if(n == 1){
return "1";
}
String s = countAndSay(n -1);
StringBuilder result = new StringBuilder();
char local = s.charAt(0);
int count = 0;
for(int i = 0;i<s.length();i++){
if(s.charAt(i) == local){
count++;
}else{
result.append(count);
result.append(local);
count = 1;
local = s.charAt(i);
}
}
result.append(count);
result.append(local);
return result.toString();
}
在递归的过程中,会以8,7,6,5,4,3,2,1的顺序传递下去,而返回的结果是以1,2,3,4,5,6,7,8的顺序返回回来。
所以处理参数为1的方法,如果n=1那么直接返回“1”;
所以在参数等于2的时候
s=1
local = 1;
for 循环 1次。
count=1;
result= 11;
参数等于3的时候
s=11;
local = 1;
for 循环 2次
count = 2;
result = 21
参数等于4的时候
s =21
local = 2
for 循环 2次
第一次 true count=1;
第二次 false result 12;
result=1211
参数等于5的时候
s=1211
local = 1
for 循环 4次
第一次 true count=1;
第二次 false result =“11”,local=2,count=1.
第三次 false result = “1112”,local= 1,count =1;
第四次 ture count = 2;
reuslt = 111221
参数等于6的时候
s=111221
local = 1;
for 循环 6次;
第一次 true count=1
第二次 true count=2;
第三次 ture count=3;
第四次 false result=“31”,local=2,count=1;
第五次 true count=2;
第六次 false result=“3122”,local=1,count=1;
result = 312211
参数等于7得时候
s= 312211
local = 3
for 循环 6次
第一次 ture count=1;
第二次 false,result=“13”,local=1,count=1;
第三次 false,result=“1311”,local=2,count=1;
第四次 true,count=2;
第五次 false result=“131122”,local=1,count=1
第六次 true count =2;
result = 13112221
参数等于8的时候
s=13112221
local=1
for 循环8次
第一次循环 true count=1;
第二次循环false,result=“11”,local=3,count=1;
第三次循环false,result=“1113”,local=1,count=1;
第四次循环true,count=2;
第五次循环false,result=“111321”,local=2,count=1;
第六次循环true,count=2;
第七次循环true,count=3;
第八次循环false,result=“11132132”,local=1,count=1;
result=“1113213211”
参与等于9的时候
s=1113213211
local=1
for 循环 10次;
第一次true count =1;
第二次 true count =2;
第三次 true count = 3;
第四次 false,result=“31”,local=3,count=1;
第五次 false,result=“3113”,local=2,count=1;
第六次 false ,result=“311312”,local=1,count=1;
第七次 false,reuslt=“31131211”,local =3 ,count =1;
第八次 false ,result = “3113121113”,local=2,count=1;
第九次 false ,result=“311312111312”,local=1,count=1
第十次 true ,count = 2;
result = 31131211131221