摘要: 接上题排列,稍作修改就可以做一个非递归的组合数了。#include <iostream>#include <vector>#include <stack>using namespace std;void permutation(int a[], int n, int k){ vector<int> b(k); stack<int> s; s.push(-1); while(!s.empty()) { if (s.size() > k) { for(int i = 0; i < k; i++) ... 阅读全文
posted @ 2012-10-31 23:37 chkkch 阅读(755) 评论(1) 推荐(0) 编辑
摘要: 打印一个数组的全排列,要求非递归。模拟递归当然会想到用栈模拟,最主要的是考虑初始的压入栈中的值,这里首先想到递归调用是用一个for循环遍历0到n-1的索引,看哪个可以用(比如k)就递归调用函数,然后返回的时候在k+1继续循环查找下去。这里的关键是如何能模拟循环的一个过程,于是我考虑到用出栈的值的下一个值来继续for循环的下一个值,于是初始从0开始,我们就可以先压入-1,然后再把它弹出栈,取下一个值作为for循环的初始值。然后当栈大小>n时打印。 1 #include <iostream> 2 #include <vector> 3 #include <sta 阅读全文
posted @ 2012-10-31 23:28 chkkch 阅读(667) 评论(0) 推荐(0) 编辑
摘要: Given an unsorted integer array, find the first missing positive integer.For example,Given[1,2,0]return3,and[3,4,-1,1]return2.Your algorithm should run inO(n) time and uses constant space.参考这里的解答:http://dl.dropbox.com/u/19732851/LeetCode/FirstMissingPositive.html主要的思想就是把对应的数放到对应的索引上,例如1放到A[1]上,这样只需要 阅读全文
posted @ 2012-10-31 11:34 chkkch 阅读(2545) 评论(2) 推荐(0) 编辑
摘要: The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...1is read off as"one 1"or11.11is read off as"two 1s"or21.21is read off as"one 2, thenone 1"or1211.Given an integern, generate thenthsequence.Note: The sequence of inte 阅读全文
posted @ 2012-10-31 11:12 chkkch 阅读(2443) 评论(0) 推荐(0) 编辑