Count and Say

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

思路

这道题自己之前做都是用的iteration的方法做,但是今天做了另一道题print numbers by recursion, 才想起来这道题完全可以用recursion来做。因为自己最近在锻炼写recursion,所以但凡可以用recursion来解决的问题我都会把思路详细地写下来。

首先这道题recursion的标志非常明显,那就是Given an integer n, generate the nth sequence. 一般这种求第N个something的题,都可以用recursion来解决,比如斐波那契数列。

  • base case: 因为是让我们求第N个数,那么我们就一步步逼近N,直到超过它。所以base case就是当position > n. 如果是void type,我们直接return就行了。否则我们就return上一层的结果。

  • main body:这是我们执行count and say的部分。但是我们还是需要分两步,那就是当position == 1,我们没有previous string,所以我们只能手动生成。否则的话我们就build upon previous string。

所以这里头我们可以看出,跟N有关的recursion问题,那么base case都是first invalid case,也就是当> n(if start from 1) or >= n (if start from 0)

代码

public class Solution {
    public String countAndSay(int n) {
        if (n <= 0){
            return "";
        }
        return helper(1, n, "");
    }
    public String helper(int position, int n, String result){
        if (position > n){
            return result;
        }
        if (position == 1){
            result = "1";
            return helper(position + 1, n, result);
        }else{
            String temp = "";
            int count = 1;
            int i = 0;
            for (i = 0; i < result.length() - 1; i++){
                if (result.charAt(i) == result.charAt(i + 1)){
                    count++;
                }else{
                    temp += Integer.toString(count) + result.charAt(i);
                    count = 1;
                }
            }
            temp += Integer.toString(count) + result.charAt(i);
            return helper(position + 1, n, temp);
        }
    }
}

复杂度

时间 O(n*k), 空间 O(1)

阅读 973

推荐阅读
liut2
用户专栏

lalala

0 人关注
7 篇文章
专栏主页
目录