leetcode9

来源:互联网 发布:网络电视怎样调出频道 编辑:程序博客网 时间:2024/05/31 11:04

Count and Say

这个题目的意思是n=1时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;n=3时,由于上次字符是11,有2个1,所以输出21;n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。

#coding=utf-8class Solution(object):    def countAndSay(self, n):        """        :type n: int        :rtype: str        """        if n==1:            return "1"        if n==2:            return "11"        s=self.countAndSay(n-1)        result=""        j=0        for i in range(1,len(s)):            if s[i]!=s[i-1]:                result+=str(len(s[j:i]))                result+=s[i-1]                j=i            if i==len(s)-1:                result+=str(len(s)-j)                result+=s[i]        return result

直接用递归就可以了,自己写递归不是太熟练,要好好练习一下。

Combination Sum

用递归,path是一个解。

#coding=utf-8class Solution(object):    def combinationSum(self, candidates, target):        """        :type candidates: List[int]        :type target: int        :rtype: List[List[int]]        """        res=[]        self.dfs(candidates,target,0,[],res)        return res    def dfs(self,nums,target,index,path,res):        if target<0:            return        if target==0:            res.append(path)            return        for i in range(index,len(nums)):            self.dfs(nums,target-nums[i],i,path+[nums[i]],res)