1 求连续子数组的最大和 (使用动态规划的思想)
int maxsum(int a[n])
//于此处,你能看到上述思路2代码(指针)的优势
{
int max=a[0]; //全负情况,返回最大数
int sum=0;
for(int j=0;j<n;j++)
{
if(sum>=0) //sum>=0的话,就加 把sum看成一个整体
sum+=a[j];
else
sum=a[j]; //sum<0了,就不加
if(sum>max)
max=sum;
}
return max;
}
2
3. 0 1背包问题
4. 二叉树中和为某一值的路径
5.字符串的全排列(没有重复字符的排列,如果重复元素要去重)
public class RecursionTree {
public static void permutation(char[] s,int from,int to) {
if(to <= 1)
return;
if(from == to) {
System.out.println(s);
} else {
for(int i=from; i<=to; i++) {
swap(s,i,from); //交换前缀,使其产生下一个前缀
permutation(s, from+1, to);
swap(s,from,i); //将前缀换回,继续做上一个前缀的排列
}
}
}
public static void swap(char[] s,int i,int j) {
char tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}
public static void main(String[] args) {
char[] s = {'a','b','c'};
permutation(s, 0, 2);
}
}
---------------------
本文来自 bitcarmanlee 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/bitcarmanlee/article/details/51558272?utm_source=copy
6.数组中下标大的数减去下标小的数的最大值即max(a[j]-a[i])j>=i
public static int max(int arr[]) {
if(arr==null||arr.length==0)
return -1;
else {
int max=0;//a[0]-a[0]的差
int i=0;
int sub=0;
int length=arr.length;
for(int j=1;j<length;j++) {
sub=arr[j]-arr[i];
if(sub>max)
max=sub;
if(sub<0)//更换最小值
i=j;
}
return max;
}
}
7.rand7(可以随机生成1到7的函数)生成rand10(可以随机生成1到10的函数)
int rand7()
{
int x=0;
do
{
x=(rand7()-1)*7+rand7();
}
while(x>40);
return x%10+1;
}