July 算法习题

https://segmentfault.com/a/1190000002710424

思想:当前层各节点首元素不同,则各节点的剩余元素也不同;下一层节点交换范围为首元素以外的元素

全排列算法:

void
swap(char *a, int i, int j){ char tmp = a[i]; a[i] = a[j]; a[j] = tmp; } void permutation(char *a, int from, int to){ if (to <= 1) return; if (from == to){ std::cout << a << std::endl; //迭代退出条件,即输出叶子节点 } else{ for (int i = from; i <= to; ++i){ swap(a, i, from); //交换当前层,即将首位元素与剩余元素分别交换 permutation(a, from + 1, to); //进入下一层 swap(a, i, from); //恢复当前层,因为进入下一层后会将a的值交换一次,所以这里再交换回来 } } }
原文地址:https://www.cnblogs.com/haiyang21/p/7860289.html