Skip to content

Commit fe11244

Browse files
committed
add jumpstep and allsort solution
1 parent c75d492 commit fe11244

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

allrange.c

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
//全排列的递归实现
2+
#include <stdio.h>
3+
#include <string.h>
4+
void Swap(char *a, char *b)
5+
{
6+
char t = *a;
7+
*a = *b;
8+
*b = t;
9+
}
10+
//k表示当前选取到第几个数,m表示共有多少数.
11+
void AllRange(char *pszStr, int k, int m)
12+
{
13+
int i;
14+
if (k == m)
15+
{
16+
static int s_i = 1;
17+
printf(" 第%3d个排列\t%s\n", s_i++, pszStr);
18+
}
19+
else
20+
{
21+
for (i = k; i <= m; i++) //第i个数分别与它后面的数字交换就能得到新的排列
22+
{
23+
Swap(pszStr + k, pszStr + i);
24+
AllRange(pszStr, k + 1, m);
25+
Swap(pszStr + k, pszStr + i);
26+
}
27+
}
28+
}
29+
void Foo(char *pszStr)
30+
{
31+
AllRange(pszStr, 0, strlen(pszStr) - 1);
32+
}
33+
int main()
34+
{
35+
char szTextStr[] = "1234";
36+
printf("%s 's all sort list below:\n", szTextStr);
37+
Foo(szTextStr);
38+
return 0;
39+
}

jumpsteps.c

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
//全排列的递归实现
2+
#include <stdio.h>
3+
#include <string.h>
4+
/*一个人上台阶可以一次上1个,2个,或者3个,问这个人上n层的台阶,总共有几种走法?打印出走法*/
5+
/* 这是最笨也是最简单的解法 */
6+
7+
static int eachsteps[] = {1,2,3}; /*store what step we can choose */
8+
static int step_type_no = sizeof(eachsteps) / sizeof(eachsteps[0]); /* store choose number */
9+
10+
int jump_steps(int stepnum) {
11+
static int walkstep[100]; /* store walk choice*/
12+
static int walkstep_idx = 0; /* store walk step */
13+
int i;
14+
int walk_no = 0;
15+
if(stepnum == 0) {
16+
/* print step choice */
17+
for (i = 0; walkstep[i] != 0; i++)
18+
printf("%d ", walkstep[i]);
19+
printf("\n");
20+
21+
return 1;
22+
}
23+
for (i = 0; i < step_type_no; i++) {
24+
walkstep[walkstep_idx++] = eachsteps[i]; /* remember this step choice in walkstep */
25+
if(stepnum - eachsteps[i] >= 0)
26+
walk_no += jump_steps(stepnum - eachsteps[i]);
27+
walkstep[walkstep_idx--] = 0; /* pop element */
28+
}
29+
return walk_no;
30+
}
31+
32+
int test_jump_steps(int argc, const char *argv[])
33+
{
34+
printf("number is %d", jump_steps(5));
35+
return 0;
36+
}

0 commit comments

Comments
 (0)