啊啊啊啊.好怀念这样的用递归保存路径然后打印出来的题目啊.好久没遇到了. 分了两种,一种是能够反复使用数组中数字的,一种是每一个数字仅仅能用一次的.事实上没有多大差别,第一种每次进入递归的时候都要从头開始尝试.另外一种要找一个标记的数组,把已经用到过的排除掉,就像生成全排列时的做法一样. 跟我一样用引用保存中间结果的话.要注意回退的情况. 另外一种回退时,要把用到的那个数也恢复为可用,就全然像全排列时做的一样.破例贴两个题的代码.由于他们是在是不值得用两片文章来写. class Solution…
[题目] Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. The same repeated number may be chosen from candidates unlimi…
1. Combination Sum Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. No…
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combination. Note: All numbers (including target) will be posi…
39. Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (inc…
在更新上面一道题的时候我就想,是不是另一道打印路径的,果不其然啊. 这样的题非经常见的,做法也非常easy,我是用一个引用的vector来存,满足条件之后直接压入结果集中,当然也能够用数组之类的,都一样.用引用须要注意的问题就是递归进行到后面的时候会对栈中的上层状态产生影响,当然能够用传值的方法来避免这个问题,可是那样子开销太大了(每次船建和销毁一个类对象,不是明智的选择).那么就是要回退,那什么时候回退,回退多少次呢?我觉得能够这样确定,在一层递归中,压入和弹出要成对出现,在这种方法中压入了几…
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.Each number in candidates may only be used once in the combination. Note: All num…
能够用递归简洁的写出,可是会超时. dp嘛.这个问题须要从后往前算,最右下角的小规模是已知的,边界也非常明显,是最后一行和最后一列,行走方向的限制决定了这些位置的走法是唯一的,能够先算出来.然后不断的往前推算. 用distance[i][j]保存从当前位置走到最右下角所需的最短距离,状态转移方程是从distance[i+1][j]和distance[i][j+1]中选一个小的,然后再加上自身的. 代码非常easy理解,这就是dp的魅力.空间上是能够优化的,由于当前状态仅仅与后一行和后一列有关系.…
当有反复元素的时候呢? 不用拍脑袋都会想到一种方法,也是全部有反复元素时的通用处理方法,维护一个set,假设这个元素没增加过就增加,增加过了的忽略掉.可是,在这道题上这个通用方法竟然超时了! 怎么办?想一下为什么会这样,如果我们要排列的数字是1111112,当当前的排列中没有1时,取哪个1生成一遍,都是一样的.仅仅有当前面的1都用过了,必须轮到这个1出场的时候,它才会有价值.更明白一点说,如果我们要在生成的排列中放两个1,那么这两个1是原来的哪两个根本无所谓,不断的选,终于的结果肯定一样,可是当…
很自然的推广,假设去掉全然二叉树的条件呢?由于这个条件不是关键,因此不会影响整体的思路.做法依旧是每次找到一层的起点,然后一层一层的走. 假设是全然二叉树的话,每层的起点就是上一层起点的左孩子,兄弟之间的链接也简单,直接找相应父亲的左右孩子就可以. 一般二叉树时,起点应该是上一层第一个有孩子节点的左孩子,或者没有左孩子时.是他的右孩子. 为了能在孩子层中不断链接,我们必须保存当孩子层的前一个节点,当当前层找到一个节点有孩子,就接到这个pre节点后面,然后更新pre节点的指向. class Sol…