Java生成子数组/子字符串与子序列

子数组/子串

子数组/子串是数组/字符串的连续部分。在另一个数组/字符串内部的一个数组/字符串。例如,考虑数组[1、2、3、4]。有10个非空子数组。子栏位是(1),(2),(3),(4),(1,2),(2,3),(3,4),(1,2,3),(2,3, 4)和(1,2,3,4)。通常,对于大小为n的数组/字符串,有n *(n + 1)/ 2个非空子数组/子字符串。
如何生成所有子数组? 

我们可以运行两个嵌套循环,外部循环选择开始元素,内部循环将被选择元素右边的所有元素视为子数组的结束元素。 

package SubarraySubstringvsSubsequence;

//Java program toto generate all possible subarrays/subArrays
//Complexity- O(n^3) */

class Subarray {
	static int arr[] = new int[] { 1, 2, 3, 4 };

// Prints all subarrays in arr[0..n-1]
	static void subArray(int n) {
		// Pick starting point
		for (int i = 0; i < n; i++) {
			// Pick ending point
			for (int j = i; j < n; j++) {
				// Print subarray between current starting
				// and ending points
				for (int k = i; k <= j; k++) {
					System.out.print(arr[k] + " ");
				}
				System.out.println();
			}
		}
	}

// Driver method to test the above function
	public static void main(String[] args) {
		System.out.println("All Non-empty Subarrays");
		subArray(arr.length);

	}
}

输出: 

所有非空子数组
1 
1 2 
1 2 3 
1 2 3 4 
2 
2 3 
2 3 4 
3 
3 4 
4

子序列 
子序列是可以从另一个序列由零个或多个元素中导出,而不改变其余元素的顺序的序列。 
对于同一示例,有15个子序列。它们是(1),(2),(3),(4),(1,2),(1,3),(1,4),(2,3),(2,4),(3 ,4),(1,2,3),(1,2,4),(1,3,4),(2,3,4),(1,2,3,4)。更笼统地说,对于一个大小为n的序列,我们总共可以有(2 n -1)个非空子序列。 

如何生成所有子序列? 
我们可以使用算法来生成用于生成所有子序列的功率集。 

package SubarraySubstringvsSubsequence;

/*  Java code to generate all possible subsequences.
Time Complexity O(n * 2^n) */

import java.math.BigInteger;

class Subsequence {
	static int arr[] = new int[] { 1, 2, 3, 4 };

	static void printSubsequences(int n) {
		/* Number of subsequences is (2**n -1) */
		int opsize = (int) Math.pow(2, n);

		/* Run from counter 000..1 to 111..1 */
		for (int counter = 1; counter < opsize; counter++) {
			for (int j = 0; j < n; j++) {
				/*
				 * Check if jth bit in the counter is set If set then print jth element from
				 * arr[]
				 */

				if (BigInteger.valueOf(counter).testBit(j))
					System.out.print(arr[j] + " ");
			}
			System.out.println();
		}
	}

// Driver method to test the above function
	public static void main(String[] args) {
		System.out.println("All Non-empty Subsequences");
		printSubsequences(arr.length);
	}
}

输出: 

所有非空子序列
1 
2 
1 2 
3 
1 3 
2 3 
1 2 3 
4 
1 4 
2 4 
1 2 4 
3 4 
1 3 4 
2 3 4 
1 2 3 4

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值