摘要: 题目:Follow up for N-Queens problem.Now, instead outputting board configurations, return the total number of distinct solutions.思路:与N queens 一样代码:class Solution {public: bool isOK(vector<int> oneSolution, int k, int val){ for (int i=0; i<k; i++){ if (oneSol... 阅读全文
posted @ 2013-04-30 10:19 tanghulu321 阅读(83) 评论(1) 推荐(0) 编辑
摘要: 题目:You are climbing a stair case. It takesnsteps to reach to the top.Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?思路: 此题可以由迭代或DP解决,在此贴一个 top down的DP代码:class Solution {public: int helper(int n, vector<int> &map){ if (n < 0) retu... 阅读全文
posted @ 2013-04-30 07:40 tanghulu321 阅读(155) 评论(0) 推荐(0) 编辑
摘要: 题目:Given an integern, return all distinct solutions to then-queens puzzle.Each solution contains a distinct board configuration of then-queens' placement, where'Q'and'.'both indicate a queen and an empty space respectively.思路: 回溯法,首先建立一个备选答案的vector,每次向其中添加一个经过检查可以添加的元素,如果搜索深度达到n则 阅读全文
posted @ 2013-04-29 05:01 tanghulu321 阅读(191) 评论(0) 推荐(0) 编辑
摘要: 与上一题相同。 class Solution { public: int calLen(ListNode *node) { int len = 0; while(node) { len++; node = node->next; } return len; } void createTree(ListNode *node, int start, int end, TreeNode *&tmpRoot) { ... 阅读全文
posted @ 2013-04-15 03:22 tanghulu321 阅读(98) 评论(0) 推荐(0) 编辑
摘要: 一开始用的第一种解法,但是大测试内存超了,所以不能迭代的时候不能每次返回一个TreeNode,而是需要建立一个引用,每一次修改引用可以节省空间。时间复杂度来说都是一样的。class Solution {public: TreeNode *build(vector<int> num, int start, int end){ if (start > end) return NULL; int mid = (start + end) / 2; TreeNode *tmpRoot = new TreeNode(num[m... 阅读全文
posted @ 2013-04-15 03:05 tanghulu321 阅读(127) 评论(0) 推荐(0) 编辑
摘要: 思路:此题很简单,只需用DFS每次添加一个元素即可。 1 class Solution { 2 public: 3 4 void DFS(vector<int> candidates, int target, vector<vector<int> > &result,int k,vector<int> a){ 5 6 if (k == target/min(candidates.front(),candidates.back())+1) return; 7 if (a.size() != 0){ 8 ... 阅读全文
posted @ 2013-04-12 22:24 tanghulu321 阅读(127) 评论(0) 推荐(0) 编辑