1)求全排列,采用递归分析,刚开始忘了 将数组恢复原样,结果运行半天都是错误:
代码
private void button2_Click(object sender, EventArgs e)
{
perm(a, 0, 2);
}
private void perm(int[] list, int i, int n)
{
int j;
if (i == n)
{
listprint(list);
}
else
{
for (j = i; j <= n; j++)
{
SWAP(ref list[i], ref list[j]);
perm(list, i + 1, n);
SWAP(ref list[i], ref list[j]);//一定要将数组恢复原样
}
}
}
private void SWAP(ref int a, ref int b)
{
int c = a;
a = b;
b = c;
}
{
perm(a, 0, 2);
}
private void perm(int[] list, int i, int n)
{
int j;
if (i == n)
{
listprint(list);
}
else
{
for (j = i; j <= n; j++)
{
SWAP(ref list[i], ref list[j]);
perm(list, i + 1, n);
SWAP(ref list[i], ref list[j]);//一定要将数组恢复原样
}
}
}
private void SWAP(ref int a, ref int b)
{
int c = a;
a = b;
b = c;
}
2)arraylist添加结构体单元时时,不需要每次都new一个结构体单元
代码
public struct pcoordinate
{
public int pX;
public int pY;
}
ArrayList lt = new ArrayList();
private void button1_Click(object sender, EventArgs e)
{
pcoordinate pc = new pcoordinate();
pc.pX = 1;
pc.pY = 1;
lt.Add(pc);
//不需要重新new一个pcoordinate,直接修改值添加到arraylist,不会改变原来的值
pc.pX = 2;
pc.pY = 2;
lt.Add(pc);
pc.pX = 3;
pc.pY = 3;
lt.Add(pc);
foreach (pcoordinate p in lt)
{
listBox1.Items.Add(p.pX.ToString() + " " + p.pY.ToString());
}
}
{
public int pX;
public int pY;
}
ArrayList lt = new ArrayList();
private void button1_Click(object sender, EventArgs e)
{
pcoordinate pc = new pcoordinate();
pc.pX = 1;
pc.pY = 1;
lt.Add(pc);
//不需要重新new一个pcoordinate,直接修改值添加到arraylist,不会改变原来的值
pc.pX = 2;
pc.pY = 2;
lt.Add(pc);
pc.pX = 3;
pc.pY = 3;
lt.Add(pc);
foreach (pcoordinate p in lt)
{
listBox1.Items.Add(p.pX.ToString() + " " + p.pY.ToString());
}
}
结果:1 1
2 2
3 3
而不是1 1
1 1
1 1